Explorar el Código

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

hzp hace 8 años
padre
commit
24a45f6d93
Se han modificado 100 ficheros con 7207 adiciones y 4970 borrados
  1. 29 21
      patient-co-statistics/pom.xml
  2. 1 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/Application.java
  3. 49 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/AsyncConfig.java
  4. 36 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java
  5. 40 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/WebSecurityConfig.java
  6. 3 3
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/JobFactory.java
  7. 1 2
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/SchedulerConfig.java
  8. 15 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java
  9. 103 5
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java
  10. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/ConsultTeamDao.java
  11. 1 28
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorAdminTeamDao.java
  12. 4 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorDao.java
  13. 2 19
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/HospitalDao.java
  14. 3 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/PatientDao.java
  15. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java
  16. 7 7
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/SignFamilyDao.java
  17. 2 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/SignPatientLabelInfoDao.java
  18. 63 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/data/DataHandingService.java
  19. 34 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/data/DataHandlingController.java
  20. 167 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/ConsultDataFilter.java
  21. 185 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/FollowUpDataFilter.java
  22. 177 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/HealthGuideDataFilter.java
  23. 477 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/SignDataFilter.java
  24. 80 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/extract/DBExtract.java
  25. 170 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/extract/DBPageExtract.java
  26. 31 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/CacheModel.java
  27. 73 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/ErrorModel.java
  28. 51 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/FilterModel.java
  29. 109 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/LogModel.java
  30. 192 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/mycache/CachePool.java
  31. 2 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/Level1Role.java
  32. 7 3
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/Level2Role.java
  33. 0 88
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/PatientAgeRole.java
  34. 0 69
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/PatientSexRole.java
  35. 211 80
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/DBStorage.java
  36. 942 62
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/RedisStorage.java
  37. 51 154
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AllSignExpenseStatusJob.java
  38. 37 152
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AllSignJob.java
  39. 35 148
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ChangeSignJob.java
  40. 32 3
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/Constant.java
  41. 36 120
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ConsultJob.java
  42. 269 1355
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentDayAllQuotaJob.java
  43. 53 164
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/FollowUpJob.java
  44. 38 133
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/HealthGuideJob.java
  45. 36 163
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/HealthSignJob.java
  46. 1 2
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/QuartzHelper.java
  47. 46 334
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignAgeGroupDiseaseJob.java
  48. 130 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignExpenseStatusJob.java
  49. 84 556
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignJob.java
  50. 34 146
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/UnSignJob.java
  51. 34 146
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/WaitSignJob.java
  52. 9 9
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/check/CheckSignJob.java
  53. 5 5
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/consult/ConsultTeam.java
  54. 11 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/doctor/Doctor.java
  55. 7 29
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamily.java
  56. 100 22
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/JobService.java
  57. 4 3
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/PatientDiseaseToLabel.java
  58. 50 16
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/PatientGroupToLabelRunnable.java
  59. 6 5
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/SignTeamAndGroupRunnable.java
  60. 27 25
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/IdCardUtil.java
  61. 45 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/JsonDateValueProcessor.java
  62. 16 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/JsonUtil.java
  63. 64 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/MD5.java
  64. 63 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/SpringUtil.java
  65. 107 31
      patient-co-statistics/src/main/resources/application.yml
  66. 1 1
      patient-co-statistics/src/main/resources/quartz.properties
  67. 23 0
      patient-co-wlyy/pom.xml
  68. 7 11
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/dict/SystemDict.java
  69. 7 11
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/dict/SystemDictList.java
  70. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/doctor/profile/Doctor.java
  71. 88 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/login/LoginLog.java
  72. 53 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/PatientFamilyMember.java
  73. 2 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamLogDao.java
  74. 6 7
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorAdminTeamDao.java
  75. 7 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorDao.java
  76. 6 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamDao.java
  77. 4 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamMemberDao.java
  78. 12 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/login/LoginLogDao.java
  79. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/organization/HospitalDao.java
  80. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java
  81. 43 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientFamilyMemberDao.java
  82. 13 6
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java
  83. 142 67
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  84. 79 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java
  85. 20 6
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java
  86. 19 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java
  87. 382 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyMemberService.java
  88. 14 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyService.java
  89. 1 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java
  90. 702 718
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  91. 42 23
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  92. 97 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/DrugService.java
  93. 59 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/HealthDataService.java
  94. 94 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/HospitalizationService.java
  95. 220 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/InspectionService.java
  96. 224 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/OutpatientService.java
  97. 94 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/RegDeptSpeDoctorService.java
  98. 8 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java
  99. 23 4
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  100. 0 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsAllService.java

+ 29 - 21
patient-co-statistics/pom.xml

@ -7,7 +7,9 @@
    <version>1.0.0</version>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>
    <!--打成war包需要的配置-->
    <packaging>war</packaging>
    <!--<packaging>jar</packaging>-->
    <name>patient-co-statistics</name>
    <properties>
@ -29,7 +31,7 @@
        <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.7.3</version.jedis>
        <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>
@ -37,7 +39,7 @@
        <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.1</version.quartz>
        <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>
@ -345,11 +347,11 @@
                <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-security</artifactId>
                <version>${version.spring-boot}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
@ -369,6 +371,7 @@
                <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>
@ -378,25 +381,30 @@
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.0.RELEASE</version>
            <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>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-ssh</artifactId>
                <version>2.10</version>
            </extension>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http-lightweight</artifactId>
                <version>2.10</version>
            </extension>
        </extensions>
        <plugins>
            <!--打成war包需要的配置-->
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>

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

@ -3,6 +3,7 @@ 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.

+ 49 - 0
patient-co-statistics/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;
    }
}

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

@ -0,0 +1,36 @@
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();
    }
}

+ 40 - 0
patient-co-statistics/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");
    }
}

+ 3 - 3
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/JobFactory.java

@ -1,4 +1,4 @@
package com.yihu.wlyy.statistics.config;
package com.yihu.wlyy.statistics.config.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
@ -16,9 +16,9 @@ public class JobFactory extends AdaptableJobFactory {
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
    // 调用父类的方法
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
    // 进行注入
       // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }

+ 1 - 2
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/SchedulerConfig.java

@ -1,4 +1,4 @@
package com.yihu.wlyy.statistics.config;
package com.yihu.wlyy.statistics.config.quartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
@ -6,7 +6,6 @@ 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.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;

+ 15 - 0
patient-co-statistics/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);
    }
}

+ 103 - 5
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java

@ -36,8 +36,9 @@ public class JobController extends BaseController {
    @ApiOperation(value = "根据ID立即单个任务")
    @RequestMapping(value = "startNowById", method = RequestMethod.GET)
    public String startNowById(
            @ApiParam(name = "id", value = "任务ID")@RequestParam(value = "id", required = true) String id) {
            @ApiParam(name = "id", value = "任务ID", required = true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.cleanCache();
            jobService.startNowById(id);
            return success("启动成功!");
        } catch (Exception e) {
@ -56,6 +57,7 @@ public class JobController extends BaseController {
    @RequestMapping(value = "productDataByDay", method = RequestMethod.GET)
    public String productDataByDay(  @ApiParam(name = "day", value = "距离今天的天数(如果是要生成昨天的数据,day=1)")@RequestParam(value = "day", required = true) int day) {
        try {
            jobService.cleanCache();
            jobService.productDataByDay(day);
            return success("启动成功!");
        } catch (Exception e) {
@ -74,6 +76,7 @@ public class JobController extends BaseController {
    @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.cleanCache();
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
@ -81,7 +84,47 @@ public class JobController extends BaseController {
            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.cleanCache();
            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.cleanCache();
            jobService.productDataByDayToDayAndId(start,end,id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的某一个指标的数据
     *
@ -94,6 +137,7 @@ public class JobController extends BaseController {
            @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.cleanCache();
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
@ -113,6 +157,7 @@ public class JobController extends BaseController {
            @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.cleanCache();
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
@ -130,7 +175,7 @@ public class JobController extends BaseController {
    @ApiOperation(value = "启动单个任务")
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(
            @ApiParam(name="id",required=true)@RequestParam(value = "id", required = true) String id) {
            @ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
@ -148,7 +193,7 @@ public class JobController extends BaseController {
     */
    @ApiOperation(value = "停止单个任务")
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(@ApiParam(name="id",required=true)@RequestParam(value = "id", required = true)String id) {
    public String stopById(@ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
@ -206,6 +251,38 @@ public class JobController extends BaseController {
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动判断的任务
     *
     * @return
     */
    @ApiOperation(value = "启动清除缓存的任务")
    @RequestMapping(value = "startCleanCacheJob", method = RequestMethod.GET)
    public String startCleanCacheJob() {
        try {
            jobService.startCleanCacheJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止判断的任务
     *
     * @return
     */
    @ApiOperation(value = "停止清除缓存的任务")
    @RequestMapping(value = "stopCleanCacheJob", method = RequestMethod.GET)
    public String stopCleanCacheJob() {
        try {
            jobService.stopCleanCacheJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动所有任务
     *
@ -222,7 +299,28 @@ public class JobController extends BaseController {
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "清除緩存")
    @RequestMapping(value = "cleanCache", method = RequestMethod.GET)
    public String cleanCache() {
        try {
            jobService.cleanCache();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "查看緩存情况")
    @RequestMapping(value = "seeCache", method = RequestMethod.GET)
    public String seeCache() {
        try {
            String message=jobService.seeCache();
            return write(200,message);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    //@RequestMapping(value = "startaaaa", method = RequestMethod.GET)
    public String startaaaa() {
        try {

+ 1 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/ConsultTeamDao.java

@ -114,6 +114,6 @@ public interface ConsultTeamDao extends PagingAndSortingRepository<ConsultTeam,
    @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.adminTeamId is null")
	@Query("FROM ConsultTeam a where a.type=?1 and a.adminTeamCode is null")
	List<ConsultTeam> findByTypeAndAdminTeamIdIsNull(Integer s);
}

+ 1 - 28
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorAdminTeamDao.java

@ -16,36 +16,9 @@ import java.util.List;
public interface DoctorAdminTeamDao extends
        PagingAndSortingRepository<AdminTeam, Long>,
        JpaSpecificationExecutor<AdminTeam> {
    /**
     * 团队内,全科医生的签约数。
     *
     * @param doctorCode
     * @param teamId
     * @return
     */
    @Query("SELECT count(s) FROM SignFamily s WHERE doctor = :doctorCode AND adminTeamId = :teamId")
    Integer getDoctorSignCount(@Param(value = "doctorCode") String doctorCode,
                               @Param(value = "teamId") long teamId);
    /**
     * 团队内,健康管理师的签约数。
     *
     * @param healthDoctorCode
     * @param teamId
     * @return
     */
    @Query("SELECT count(s) FROM SignFamily s WHERE doctorHealth = :healthDoctorCode AND adminTeamId = :teamId")
    Integer getHealthDoctorSignCount(@Param(value = "healthDoctorCode") String healthDoctorCode,
                                     @Param(value = "teamId") long teamId);
    @Query("SELECT t.id from AdminTeam t WHERE t.leaderCode = :leaderCode")
    Long findIdByLeaderCode(@Param("leaderCode") String leaderCode);
    @Query(" from AdminTeam t")
    @Query(" from AdminTeam t where length(t.orgCode) = 10")
    List<AdminTeam> findAllTeam();
    @Query("SELECT t from AdminTeam t WHERE t.leaderCode = :leaderCode")
    AdminTeam findByLeaderCode(@Param("leaderCode") String leaderCode);
}

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

@ -108,4 +108,8 @@ public interface DoctorDao extends PagingAndSortingRepository<Doctor, Long>, Jpa
    @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();
}

+ 2 - 19
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/HospitalDao.java

@ -15,28 +15,11 @@ import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface HospitalDao extends PagingAndSortingRepository<Hospital, Long>,JpaSpecificationExecutor<Hospital>  {
	// 根據CODE查詢医院名称
	@Query("select p from Hospital p where p.code = ?1")
	Hospital findByCode(String code);
	@Query("select a from Hospital a where a.name like ?1 and a.id<?2")
	Page<Hospital> getHospitalList(String query, long id, Pageable pageRequest);
	@Query("select p from Hospital p where p.del = 1 and p.level in (1,2) ")
	List<Hospital> findAllHospital();
	@Query("select p from Hospital p where p.del = 1 and p.level = 2 ")
	List<Hospital> findAllSqHospital();
	@Query("select p from Hospital p where p.del = 1 and p.level = 2 and town = ?1")
	List<Hospital> findAreaSqHospital(String town);
	@Query("select p from Hospital p where p.del = 1 and p.level =2 and p.centerSite='00'")
	@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'")
	@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();
	@Query("select p from Hospital p where p.town = ?1 and p.del='1' and p.level =2 and p.centerSite='00'")
	List<Hospital> findByTownCode(String town);
}

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

@ -50,4 +50,7 @@ public interface PatientDao extends PagingAndSortingRepository<Patient, Long> {
	@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();
}

+ 1 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java

@ -18,7 +18,7 @@ public interface QuartzJobConfigDao extends PagingAndSortingRepository<QuartzJob
    @Query(" FROM QuartzJobConfig a WHERE a.status=?1 and a.del='1'")
    List<QuartzJobConfig> findByAll(String s);
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14,15)  and a.del='1' ")
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14,15,16)  and a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")

+ 7 - 7
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/SignFamilyDao.java

@ -18,27 +18,27 @@ 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 unix_timestamp(a.czrq)=unix_timestamp( ?1 )  ")
	@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 unix_timestamp(a.applyDate)>=unix_timestamp(?1) and unix_timestamp(a.applyDate)<unix_timestamp(?2) and a.expensesStatus=1 ")
	@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  unix_timestamp(a.applyDate)<=unix_timestamp(?1) and a.expensesStatus=1 ")
	@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  unix_timestamp(a.applyDate)<=unix_timestamp(?1) ")
	@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 unix_timestamp(a.applyUnsignDate)>=unix_timestamp(?1) and unix_timestamp(a.applyUnsignDate)<unix_timestamp(?2) and a.expensesStatus=1")
	@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 unix_timestamp(a.patientApplyDate)>=unix_timestamp(?1) and unix_timestamp(a.patientApplyDate)<unix_timestamp(?2)")
	@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 unix_timestamp(a.patientApplyDate)>=unix_timestamp(?1) and unix_timestamp(a.patientApplyDate)<unix_timestamp(?2) and a.expensesStatus=1 ")
	@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);
	// 查询同步数据

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

@ -63,4 +63,6 @@ public interface SignPatientLabelInfoDao extends
     */
    @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);
}

+ 63 - 0
patient-co-statistics/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/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());
        }
    }
}

+ 167 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/ConsultDataFilter.java

@ -0,0 +1,167 @@
package com.yihu.wlyy.statistics.etl.dataFilter;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
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.util.*;
/**
 * Created by Administrator on 2016.10.17.
 * 咨询数据清洗
 */
@Component
@Scope("prototype")
public class ConsultDataFilter {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();//错误信息
    public FilterModel filter(List<ConsultTeam> consultTeams, String sql, String filterDate){
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        //数据过滤清洗出脏数据  -----------start
        for(ConsultTeam consultTeam:consultTeams){
            ETLModel etlModel=new ETLModel();
            Long adminId=consultTeam.getAdminTeamCode();
            if(adminId == null||adminId<=0) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_null));
                isAll=false;
                continue;
            }
            String teamCode = consultTeam.getAdminTeamCode()+"";//行政的团队的id
            AdminTeam adminTeam=adminTeamMap.get(teamCode);
            if(adminTeam == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode = adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            //统计区 ---------------start--------------
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_noExist));
                isAll=false;
                continue;
            }
            String town=hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_null));
                isAll=false;
                continue;
            }
            Town townObj=townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_noExist));
                isAll=false;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setAllNum(consultTeams.size());
        logModel.setSuccess(isAll);
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
       // String message=saveContent(consultTeams.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }
    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}

+ 185 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/FollowUpDataFilter.java

@ -0,0 +1,185 @@
package com.yihu.wlyy.statistics.etl.dataFilter;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
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.util.*;
/**
 * Created by Administrator on 2016.10.17.
 * 随访数据清洗
 */
@Component
@Scope("prototype")
public class FollowUpDataFilter {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();//错误信息
    public FilterModel filter(List<Map<String,Object>> plans, String sql, String filterDate){
        //查找出系统全部的医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        for(Map<String,Object> plan:plans){
            ETLModel etlModel=new ETLModel();
            Object idCard=plan.get("id_card");//得到隨訪的身份證
            if(StringUtils.isEmpty(idCard)){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_idcard_null));
                isAll=false;
                continue;
            }
            SignFamily signFamily=signFamilyDao.findByIdcard(idCard.toString());
            if(signFamily==null){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_sign_noExist));
                isAll=false;
                continue;
            }
            Long adminTeamId=signFamily.getAdminTeamCode();
            if(adminTeamId==null||adminTeamId<=0){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_adminTeam_null));
                isAll=false;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamCode());
            if(adminTeam==null){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_adminTeam_noExist));
                isAll=false;
                continue;
            }
            //统计机构------------------start ------------------
            //判断医生属于哪个机构
            String orgCodeTemp="";
            String orgCode=adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital==null){
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_hospital_noExist));
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(plan.get("id").toString(),ErrorModel.fv_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setAllNum(plans.size());
        logModel.setSuccess(isAll);
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        // String message=saveContent(plans.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }
    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}

+ 177 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/HealthGuideDataFilter.java

@ -0,0 +1,177 @@
package com.yihu.wlyy.statistics.etl.dataFilter;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
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.util.*;
/**
 * Created by Administrator on 2016.10.17.
 */
@Component
@Scope("prototype")
public class HealthGuideDataFilter {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();//错误信息
    public FilterModel filter(List<PatientHealthGuidance> patientHealthGuidances, String sql, String filterDate){
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        //数据过滤清洗出脏数据  -----------start
        for(PatientHealthGuidance patientHealthGuidance:patientHealthGuidances){
            ETLModel etlModel=new ETLModel();
            String patient=patientHealthGuidance.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_sign_noExist));
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamCode()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_adminTeam_null));
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            //统计机构 -----------------start---------------------
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_noExist));
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(patientHealthGuidances.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(patientHealthGuidances.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }
    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}

+ 477 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/SignDataFilter.java

@ -0,0 +1,477 @@
package com.yihu.wlyy.statistics.etl.dataFilter;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.IdCardUtil;
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.util.*;
/**
 * Created by Administrator on 2016.10.16.
 * 签约数据的过滤
 */
@Component
@Scope("prototype")
public class SignDataFilter {
    public static String level2Sex="1";//性别
    public static String level2Age="2";//年龄
    public static String level2Group="3";//分组
    public static String level2Expenses="4";//费用
    public static String level2Health="5";//健康服务分布
    public static String level2Age2="6";//年龄
    public static String level3Disease="1";//疾病分组
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private CachePool cachePool;
    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();
    private int count=0;
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String sql){
        return filterCommon(signFamilies,null,null,sql,null);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param filterDate 不传默认是但在的时间
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String sql,String filterDate){
        return filterCommon(signFamilies,null,null,sql,filterDate);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String level2Key,String sql,String filterDate){
        return filterCommon(signFamilies,level2Key,null,sql,filterDate);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param level3Key 三级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String level2Key,String level3Key,String sql,String filterDate){
        return filterCommon(signFamilies,level2Key,level3Key,sql,filterDate);
    }
    /**
     * 公共的抽取方法
     *  @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param level3Key 三级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    private FilterModel filterCommon(List<SignFamily> signFamilies ,String level2Key,String level3Key,String sql,String filterDate) {
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        List<ETLModel> etlModelList=new ArrayList<>();//返回的ETL數據
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        for (int i=0;i<signFamilies.size();i++){
            SignFamily signFamily=signFamilies.get(i);
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_null));
                isAll=false;
                errorCount++;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
           Long adminId=signFamily.getAdminTeamCode();
            if(adminId == null||adminId<=0) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_adminTeam_null));
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(adminId+"");
            if(adminTeam == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_adminTeam_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error));
                isAll=false;
                errorCount++;
                continue;
            }
            //设置二级维度的Key
            String returnLevel2Key=getLevel2Key(level2Key,signFamily);
            String returnLevel3Key=getLevel3Key(level3Key,signFamily);
            if(StringUtils.isEmpty(returnLevel2Key)){
                //没有二级维度
                ETLModel etlModel=new ETLModel();
                etlModel.setAdminTeam(adminTeam.getId()+"");
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModelList.add(etlModel);
            }else{
                String[] level2Keys=returnLevel2Key.split(",");
                for(int j=0;j<level2Keys.length;j++){
                    ETLModel etlModel=new ETLModel();
                    etlModel.setLevel2Key(level2Keys[j]);
                    etlModel.setLevel3Key(returnLevel3Key);
                    etlModel.setAdminTeam(adminTeam.getId()+"");
                    etlModel.setHospital(orgCodeTemp);
                    etlModel.setTown(hospital.getTown());
                    etlModel.setCity(Constant.city);
                    etlModelList.add(etlModel);
                }
            }
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(signFamilies.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(signFamilies.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModelList,isAll);
    }
    private String getLevel3Key(String level3Key, SignFamily signFamily) {
        String returnLevel3Key=null;
        if(!StringUtils.isEmpty(level3Key)){
            switch (level3Key){
                //疾病
                case "1" :{
                    returnLevel3Key = getDisease(signFamily);
                    break;
                }
            }
        }
        return returnLevel3Key;
    }
    /**
     * 根据签约表的患者code从缓存得到疾病标签
     * @param signFamily
     * @return
     */
    private String getDisease(SignFamily signFamily) {
        boolean hasGXY = false;//有高血压
        boolean hasTNB = false;//有糖尿病
        //如果是慢病的 统计高血压的 糖尿病  1高血压,2糖尿病  3 糖尿病和高血压 4健康人群数
        String diseaseType="4";
        //得到患者的疾病标签
        List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
        if(diseaseList!=null&&diseaseList.size()>0){
            for (String diseaseCode:diseaseList){
                if("1".equals(diseaseCode)){//判斷是否有高血壓
                    diseaseType="1";
                    hasGXY=true;
                }
                if("2".equals(diseaseCode)){//判斷是否有糖尿病
                    diseaseType="2";
                    hasTNB=true;
                }
            }
        }
        if (hasTNB&&hasGXY){
            diseaseType="3";
        }
        return diseaseType;
    }
    /**
     * 得到二级维度的key
     * @param level2Key
     * @return
     */
    private String getLevel2Key(String level2Key,SignFamily signFamily) {
        String returnLevel2Key=null;
        if(!StringUtils.isEmpty(level2Key)){
             switch (level2Key){
                 //性别
                 case "1" :{
                     returnLevel2Key = getSex(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄
                 case "2" :{
                     returnLevel2Key = getAge(signFamily);
                     return returnLevel2Key;
                 }
                 //分组
                 case "3" :{
                     //得到患者的分组标签
                     returnLevel2Key = getGroup(signFamily);
                     return returnLevel2Key;
                 }
                 //费用
                 case "4" :{
                     returnLevel2Key = getExpenses(signFamily);
                     return returnLevel2Key;
                 }
                 //健康服务分布
                 case "5" :{
                     returnLevel2Key = getHealth(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄
                 case "6" :{
                     returnLevel2Key = getAge2(signFamily);
                     return returnLevel2Key;
                 }
             }
        }
        return returnLevel2Key;
    }
    private String getAge2(SignFamily signFamily) {
        String returnLevel2Key;
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        returnLevel2Key=getAgeCode2(age);
        return returnLevel2Key;
    }
    private String getHealth(SignFamily signFamily) {
        String returnLevel2Key="0";//查找每个患者的健康分布标签
        try{
            returnLevel2Key=cachePool.getHealthGroup(signFamily.getPatient());
        }catch (Exception e){
            e.printStackTrace();
            return returnLevel2Key;
        }
        if(StringUtils.isEmpty(returnLevel2Key)){
            return "0";
        }
        return returnLevel2Key;
    }
    private String getExpenses(SignFamily signFamily) {
        if("1".equals(signFamily.getExpensesStatus())){
            count++;
        }
        String returnLevel2Key= signFamily.getExpensesStatus();
        if(StringUtils.isEmpty(returnLevel2Key)){
            returnLevel2Key="0";
        }
        return returnLevel2Key;
    }
    private String getGroup(SignFamily signFamily) {
        String returnLevel2Key="";
        String group=cachePool.getPatientGroup(signFamily.getPatient());
        if(StringUtils.isEmpty(group)){
            group="0";
        }
        StringBuffer returnLevel2KeyBuffer=new StringBuffer(group);
        //如果是慢病组  区分65岁以上还是以下   65岁以上的慢病患者是7  65岁上下是2
        if("2".equals(returnLevel2KeyBuffer.toString())){
             Integer age=IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
            if(age>65){
                returnLevel2KeyBuffer=new StringBuffer("7");
            }
        }
        if("2".equals(returnLevel2KeyBuffer.toString())||"7".equals(returnLevel2KeyBuffer.toString())){
            String returnLevel2KeyTemp="-1";
            boolean hasGXY=false;//有高血压
            boolean hasTNB=false;//糖尿病
            //得到患者的疾病标签
            List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
            if(diseaseList!=null&&diseaseList.size()>0){
                for (String diseaseCode:diseaseList){
                    if("1".equals(diseaseCode)){//判斷是否有高血壓
                        returnLevel2KeyTemp="4";
                        hasGXY=true;
                    }
                    if("2".equals(diseaseCode)){//判斷是否有糖尿病
                        returnLevel2KeyTemp="5";
                        hasTNB=true;
                    }
                }
            }
            if (hasTNB&&hasGXY){
                returnLevel2KeyTemp="6";
            }
            returnLevel2KeyBuffer.append(","+returnLevel2KeyTemp);
        }
        returnLevel2Key=returnLevel2KeyBuffer.toString();
        return returnLevel2Key;
    }
    private String getAge(SignFamily signFamily) {
        String returnLevel2Key;
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        returnLevel2Key=getAgeCode(age);
        return returnLevel2Key;
    }
    private String getSex(SignFamily signFamily) {
        String returnLevel2Key;
        try{
            returnLevel2Key= IdCardUtil.getSexForIdcard(signFamily.getIdcard());
        }catch (Exception e){
            //如果解析失败 默认是男 并且纪录解析失败的签约code
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_sex));
            return Constant.level_sex_2;
        }
        return returnLevel2Key;
    }
    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    /**
     * 根据年龄得到对应的code
     *
     * @param age
     * @return
     */
    public String getAgeCode(Integer age) {
        if (age < 7) {
            return Constant.level_age_1;
        } else if (age >= 7 && age < 18) {
            return Constant.level_age_2;
        } else if (age >= 18 && age < 30) {
            return Constant.level_age_3;
        } else if (age >= 30 && age < 50) {
            return Constant.level_age_4;
        } else if (age >= 50 && age < 65) {
            return Constant.level_age_5;
        } else {
            return Constant.level_age_6;
        }
    }
    /**
     * 根据年龄得到对应的code
     *
     * @param age
     * @return
     */
    public String getAgeCode2(Integer age) {
        if (age <= 65) {
            return Constant.level_age2_1;
        } else {
            return Constant.level_age2_2;
        }
    }
}

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

@ -0,0 +1,80 @@
package com.yihu.wlyy.statistics.etl.extract;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 数据库抽取
 */
@Component
@Scope("prototype")
public class DBExtract<T> {
    //只读库的jdbcTemplate
    private JdbcTemplate jdbcTemplate;
    /**
     * 构造注入只读库的数据源
     * @param dataSource
     */
    @Autowired(required=true)
    public DBExtract(@Qualifier(value="primaryRead") DataSource dataSource) {
        this.jdbcTemplate =new JdbcTemplate();
        this.jdbcTemplate.setDataSource(dataSource);
    }
    /**
     * 不分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<T> extract(Class<T> clazz,String sql){
        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)throws  Exception{
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @param isMultithreading 是否多线程抽取 默认否
     * @return
     */
    public List<Object> extractByPage(Class<T> clazz,String sql,String countSql,Boolean isMultithreading)throws  Exception{
        int pageSize=10000;
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<Object> extractByPage(Class<T> clazz,String sql)throws  Exception{
        int pageSize=10000;
        Boolean isMultithreading=false;
        String countSql="";
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading);
    }
}

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

@ -0,0 +1,170 @@
package com.yihu.wlyy.statistics.etl.extract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
 * Created by Administrator on 2016.10.16.
 * 分页抽取器
 */
@Component
@Scope("prototype")
public class DBPageExtract<T> {
    //只读库的jdbcTemplate
    private JdbcTemplate jdbcTemplate;
    /**
     * 构造注入只读库的数据源
     * @param dataSource
     */
    @Autowired(required=true)
    public DBPageExtract(@Qualifier(value="primaryRead") DataSource dataSource) {
        this.jdbcTemplate =new JdbcTemplate();
        this.jdbcTemplate.setDataSource(dataSource);
    }
    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) throws Exception{
        if(isMultithreading){
            if(StringUtils.isEmpty(countSql)){
                throw new Exception("countSql is null");
            }
            return MultiThreadExtract(clazz, sql,countSql, pageSize);
        }else{
            return noMultiThreadExtract(clazz, sql, pageSize);
        }
    }
    /**
     * 不用多线程抽取
     * @param clazz
     * @param sql
     * @param pageSize
     * @return
     */
    private List<T> noMultiThreadExtract(Class<T> clazz, String sql, int pageSize) {
        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)  {
        try{
            //得到数据的总数
            Integer dataCount=getCount(countSql);
            //根据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);
                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);
        }
    }
    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) {
        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) {
        String finalSql=sql+" limit "+start+","+pageSize; //拼凑分页的语句
        List<T> listTemp= jdbcTemplate.query(finalSql,new BeanPropertyRowMapper(clazz));
        addData(listTemp);
        return new AsyncResult<>(true);
    }
}

+ 31 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/CacheModel.java

@ -0,0 +1,31 @@
package com.yihu.wlyy.statistics.etl.model;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import java.util.List;
/**
 * Created by Administrator on 2016.10.19.
 * 缓存的model模型
 */
public class CacheModel {
    private List<SignFamily> signFamilies;//数据
    private String sql;//执行的sql语句
    public List<SignFamily> getSignFamilies() {
        return signFamilies;
    }
    public void setSignFamilies(List<SignFamily> signFamilies) {
        this.signFamilies = signFamilies;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
}

+ 73 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/ErrorModel.java

@ -0,0 +1,73 @@
package com.yihu.wlyy.statistics.etl.model;
/**
 * Created by Administrator on 2016.10.20.
 */
public class ErrorModel {
    private String code;//错误数据的主键
    private String type;//错误的类型
    private ErrorModel(String code, String type) {
        this.code=code;
        this.type=type;
    }
    public static ErrorModel newEM(String code, String type){
        return new ErrorModel(code,type);
    }
    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 static String sign_hospital_null="签约表中(wlyy_sign_family)中的hospital数据为空";
    public static String sign_hospital_noExist="签约表中(wlyy_sign_family)中的hospital数据不存在";
    public static String sign_hospital_isTest="签约表中(wlyy_sign_family)中的hospital数据是测试数据";
    public static String sign_adminTeam_null="签约表中(wlyy_sign_family)中的团队数据为空";
    public static String sign_adminTeam_noExist="签约表中(wlyy_sign_family)中的团队数据不存在";
    public static String sign_town_null="机构表的中的town为空";
    public static String sign_town_noExist="机构表的中的town不存在";
    public static String sign_idcard_error="签约表中(wlyy_sign_family)中的身份证错误";
    public static String sign_idcard_error_age="签约表中(wlyy_sign_family)中的身份证解析年龄失败";
    public static String sign_idcard_error_sex="签约表中(wlyy_sign_family)中的身份证解析性别失败";
    public static String consult_adminTeam_null="咨询的团队(wlyy_consult_team)中的admin_team_code数据为空";
    public static String consult_adminTeam_noExist="咨询的团队(wlyy_consult_team)中的admin_team_code数据不存在";
    public static String consult_hospital_null="咨询的团队(wlyy_consult_team)中的admin_team_code在团队表中的orgCode为空";
    public static String consult_hospital_noExist="咨询的团队(wlyy_consult_team)中的admin_team_code在团队表中的orgCode为不存在";
    public static String consult_hospital_isTest="咨询的团队(wlyy_consult_team)中的admin_team_code在团队表中的orgCode为测试机构";
    public static String consult_town_null="咨询的团队(wlyy_consult_team)中的admin_team_code在团队表中的orgCode在机构表对应的机构的town为空";
    public static String consult_town_noExist="咨询的团队(wlyy_consult_team)中的admin_team_code在团队表中的orgCode在机构表对应的机构的town不存在";
    public static String healthGuidance_sign_noExist="健康咨询中的患者所属的家庭签约不存在";
    public static String healthGuidance_adminTeam_null="健康咨询中的患者所属的家庭签约表中(wlyy_sign_family)中的团队数据为空";
    public static String healthGuidance_adminTeam_noExist="健康咨询中的患者所属的家庭签约表中(wlyy_sign_family)中的团队数据不存在";
    public static String healthGuidance_hospital_null="健康咨询中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据为空";
    public static String healthGuidance_hospital_noExist="健康咨询中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据不存在";
    public static String healthGuidance_hospital_isTest="健康咨询中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据是测试机构";
    public static String healthGuidance_town_null="健康咨询中的患者所属的家庭签约中所属机构表的中的town为空";
    public static String healthGuidance_town_noExist="健康咨询中的患者所属的家庭签约中所属机构表的中的town为不存在";
    public static String fv_sign_noExist="随访中的患者所属的家庭签约不存在";
    public static String fv_idcard_null="随访中的患者身份证为空";
    public static String fv_adminTeam_null="随访中的患者所属的家庭签约表中(wlyy_sign_family)中的团队数据为空";
    public static String fv_adminTeam_noExist="随访中的患者所属的家庭签约表中(wlyy_sign_family)中的团队数据不存在";
    public static String fv_hospital_null="随访中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据为空";
    public static String fv_hospital_noExist="随访中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据不存在";
    public static String fv_hospital_isTest="随访中的患者所属的家庭签约表中(wlyy_sign_family)中的hospital数据是测试机构";
    public static String fv_town_null="随访中的患者所属的家庭签约中所属机构表的中的town为空";
    public static String fv_town_noExist="随访中的患者所属的家庭签约中所属机构表的中的town为不存在";
}

+ 51 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/FilterModel.java

@ -0,0 +1,51 @@
package com.yihu.wlyy.statistics.etl.model;
import java.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 過濾器模型
 */
public class FilterModel {
    private LogModel logModel;
    private List<ETLModel> etlModelList;
    private Boolean isError;
    private FilterModel(){
    }
    public FilterModel( LogModel logModel, List<ETLModel> etlModelList,Boolean isError) {
        this.isError=isError;
        this.logModel = logModel;
        this.etlModelList = etlModelList;
    }
    public static FilterModel getFiltrerMode(LogModel logModel, List<ETLModel> etlModelList,Boolean isError){
        return new FilterModel(logModel,etlModelList,isError);
    }
    public LogModel getLogModel() {
        return logModel;
    }
    public void setLogModel(LogModel logModel) {
        this.logModel = logModel;
    }
    public Boolean getError() {
        return isError;
    }
    public void setError(Boolean error) {
        isError = error;
    }
    public List<ETLModel> getEtlModelList() {
        return etlModelList;
    }
    public void setEtlModelList(List<ETLModel> etlModelList) {
        this.etlModelList = etlModelList;
    }
}

+ 109 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/model/LogModel.java

@ -0,0 +1,109 @@
package com.yihu.wlyy.statistics.etl.model;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by Administrator on 2016.10.20.
 */
public class LogModel {
    private String id;//指标id
    private Integer successNum;//成功数
    private Integer errorNum;//錯誤數目
    private Integer allNum;//所有总数
    private String excuteSql;//执行的sql
    private Date endTime;//结束时间
    private List<ErrorModel> modelList = new ArrayList<>();//错误列表
    private String date;//統計的時間
    private boolean success;//是否出现异常
    @Override
    public String toString() {
        return "LogModel{" +
                "id='" + id + '\'' +
                ", successNum=" + successNum +
                ", errorNum=" + errorNum +
                ", allNum=" + allNum +
                ", excuteSql='" + excuteSql + '\'' +
                ", endTime=" + endTime +
                ", modelList=" + modelList +
                ", date='" + date + '\'' +
                ", success=" + success +
                '}';
    }
    public boolean isSuccess() {
        return success;
    }
    public void setSuccess(boolean success) {
        this.success = success;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public Integer getSuccessNum() {
        return successNum;
    }
    public Integer getErrorNum() {
        return errorNum;
    }
    public void setErrorNum(Integer errorNum) {
        this.errorNum = errorNum;
    }
    public void setSuccessNum(Integer successNum) {
        this.successNum = successNum;
    }
    public Integer getAllNum() {
        return allNum;
    }
    public void setAllNum(Integer allNum) {
        this.allNum = allNum;
    }
    public String getExcuteSql() {
        return excuteSql;
    }
    public void setExcuteSql(String excuteSql) {
        this.excuteSql = excuteSql;
    }
    public String getEndTime() {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(endTime);
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    public List<ErrorModel> getModelList() {
        return modelList;
    }
    public void setModelList(List<ErrorModel> modelList) {
        this.modelList = modelList;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}

+ 192 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/mycache/CachePool.java

@ -0,0 +1,192 @@
package com.yihu.wlyy.statistics.etl.mycache;
import com.yihu.wlyy.statistics.dao.SignPatientLabelInfoDao;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016.10.19.
 */
@Component
public class CachePool {
    /**
     * 到达量的缓存  key 是时间yyyy-MM-dd
     */
    private static Map<String,CacheModel> arriveSignFamilyExpenseStatus1Map=new HashMap<String,CacheModel>();
    /**
     * 分组标签的缓存 key 是患者code
     */
    private static Map<String,String> patientGroup=new HashMap<String,String>();
    /**
     * 健康标签的缓存 key 是患者code
     */
    private static Map<String,String> healthGroup=new HashMap<String,String>();
    /**
     * 疾病标签的缓存 key 是患者code
     */
    private static Map<String,List<String>> diseaseGroup=new HashMap<String,List<String>>();
    /**
     * 某天的签约的已扣费的到达量
     * @param date
     * @return
     * @throws Exception
     */
    public synchronized CacheModel getSignFamilysWithExpenseStatus1ByDate(String date) throws Exception{
        CacheModel model= arriveSignFamilyExpenseStatus1Map.get(date);
        if(model==null){
            model=new CacheModel();
            String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status,patient from wlyy_sign_family a " +
                    " where status in(1,2) and a.type =2  and expenses_status=1 and a.expenses_time< '"+date+ Constant.quota_date_last+"'" ;
            String sqlCount="select count(id) from wlyy_sign_family a " +
                    " where  status in(1,2) and a.type =2 and expenses_status=1 and a.expenses_time< '"+date+ Constant.quota_date_last+"'";
            //抽取數據 分页抽取
            List<SignFamily> signFamiliesTemp= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
            model.setSql(sql);
            model.setSignFamilies(signFamiliesTemp);
            arriveSignFamilyExpenseStatus1Map.put(date,model);
            return model;
        }else{
            return model;
        }
    }
    /**
     * 查询某人的分组标签
     * @param patientCode
     * @return
     * @throws Exception
     */
    public String getPatientGroup(String patientCode){
        String code=null;
        try{
            if(patientGroup.size()==0){
                initPatientGroup();
            }
            code= patientGroup.get(patientCode);
            if(StringUtils.isEmpty(code)){
                code="0";
            }
        }catch (Exception e){
            e.printStackTrace();
            return code;
        }
        return code;
    }
    private synchronized void initPatientGroup() throws  Exception{
        if(patientGroup.size()==0) {
            String sql="select patient,label from wlyy_sign_patient_label_info where label_type='1' and status=1";
            String countSql="select count(id) from wlyy_sign_patient_label_info where label_type='1' and status=1";
            List<SignPatientLabelInfo> signPatientLabelInfoList = SpringUtil.getBean(DBExtract.class).extractByPage(SignPatientLabelInfo.class,sql,countSql,true);
            for (SignPatientLabelInfo signPatientLabelInfo : signPatientLabelInfoList) {
                patientGroup.put(signPatientLabelInfo.getPatient(), signPatientLabelInfo.getLabel());
            }
        }
    }
    /**
     * 查询某人的健康标签
     * @param patientCode
     * @return
     * @throws Exception
     */
    public  String getHealthGroup(String patientCode){
        String code;
        try{
            if(healthGroup.size()==0){
                initHealthGroup();
            }
             code= healthGroup.get(patientCode);
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
        if(StringUtils.isEmpty(code)){
            code="0";
        }
        return code;
    }
    private synchronized void initHealthGroup()  throws  Exception{
        if(healthGroup.size()==0){
            String sql="select patient,label from wlyy_sign_patient_label_info where label_type='2' and status=1";
            String countSql="select count(id) from wlyy_sign_patient_label_info where label_type='2' and status=1";
            List<SignPatientLabelInfo> signPatientLabelInfoList = SpringUtil.getBean(DBExtract.class).extractByPage(SignPatientLabelInfo.class,sql,countSql,true);
            for(SignPatientLabelInfo signPatientLabelInfo:signPatientLabelInfoList){
                healthGroup.put(signPatientLabelInfo.getPatient(),signPatientLabelInfo.getLabel());
            }
        }
    }
    /**
     * 查询某人的疾病标签
     * @param patientCode
     * @return
     * @throws Exception
     */
    public  List<String> getDiseaseGroup(String patientCode) {
        try{
            if(diseaseGroup.size()==0){
                initDiseaseGroup();
            }
            List<String> code= diseaseGroup.get(patientCode);
            return code;
        }catch (Exception e){
            return null;
        }
    }
    private synchronized void initDiseaseGroup()  throws  Exception{
        if(diseaseGroup.size()==0){
            String sql="select patient,label from wlyy_sign_patient_label_info where label_type='3' and status=1";
            String countSql="select count(id) from wlyy_sign_patient_label_info where label_type='3' and status=1";
            List<SignPatientLabelInfo> signPatientLabelInfoList = SpringUtil.getBean(DBExtract.class).extractByPage(SignPatientLabelInfo.class,sql,countSql,true);
            for(SignPatientLabelInfo signPatientLabelInfo:signPatientLabelInfoList){
                if(diseaseGroup.containsKey(signPatientLabelInfo.getPatient())){
                    List<String> code= diseaseGroup.get(signPatientLabelInfo.getPatient());
                    code.add(signPatientLabelInfo.getLabel());
                    diseaseGroup.put(signPatientLabelInfo.getPatient(),code);
                }else{
                    List<String> code=new ArrayList<>();
                    code.add(signPatientLabelInfo.getLabel());
                    diseaseGroup.put(signPatientLabelInfo.getPatient(),code);
                }
            }
        }
    }
    public static void cleanAllCache() {
        arriveSignFamilyExpenseStatus1Map.clear();
        patientGroup.clear();;
        diseaseGroup.clear();
        healthGroup.clear();
    }
    public static Map<String, CacheModel> getArriveSignFamilyExpenseStatus1Map() {
        return arriveSignFamilyExpenseStatus1Map;
    }
    public static Map<String, String> getPatientGroup() {
        return patientGroup;
    }
    public static Map<String, String> getHealthGroup() {
        return healthGroup;
    }
    public static Map<String, List<String>> getDiseaseGroup() {
        return diseaseGroup;
    }
}

+ 2 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/Level1Role.java

@ -1,6 +1,7 @@
package com.yihu.wlyy.statistics.etl.role;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -14,7 +15,7 @@ import java.util.Map;
 * 1级维度 机构等级分组
 */
@Component
@Transactional
@Scope("prototype")
public class Level1Role {
    /**

+ 7 - 3
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/Level2Role.java

@ -1,6 +1,7 @@
package com.yihu.wlyy.statistics.etl.role;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -13,8 +14,9 @@ import java.util.Map;
 * Created by Administrator on 2016.10.11.
 * 二级维度 的公共的统计算法
 */
@Component
@Transactional
@Scope("prototype")
public class Level2Role {
    public List<Map<String, Map<String, List<ETLModel>>>> elt(List<Map<String, List<ETLModel>>> data) throws  Exception{
        List<Map<String, Map<String, List<ETLModel>>>> returnMapsList=new ArrayList<Map<String, Map<String, List<ETLModel>>>>();
@ -57,9 +59,11 @@ public class Level2Role {
                //如果list不存在 新建一个
                if(etlModels==null){
                    etlModels=new ArrayList<>();
                    etlModels.add(eltModel);
                    childrens.put(sexKey,etlModels);
                }else{
                    etlModels.add(eltModel);
                }
                etlModels.add(eltModel);
                childrens.put(sexKey,etlModels);
            }
            tjMap.put(oneData.getKey(),childrens);
        }

+ 0 - 88
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/PatientAgeRole.java

@ -1,88 +0,0 @@
package com.yihu.wlyy.statistics.etl.role;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016.10.09.
 * 患者性别
 */
@Component
@Transactional
public class PatientAgeRole {
    public List<Map<String, Map<String, List<ETLModel>>>> elt(List<Map<String, List<ETLModel>>> data) throws  Exception{
        List<Map<String, Map<String, List<ETLModel>>>> returnMapsList=new ArrayList<Map<String, Map<String, List<ETLModel>>>>();
        Map<String,Map<String, List<ETLModel>>> tjCityMap = new HashMap<String,Map<String, List<ETLModel>>>();//市级的统计map key 是区行政区划350200
        Map<String,Map<String, List<ETLModel>>> tjTownMap = new HashMap<String,Map<String, List<ETLModel>>>();//区级的统计map key 是区行政区划350206
        Map<String,Map<String, List<ETLModel>>> tjOrgMap = new HashMap<String,Map<String, List<ETLModel>>>();//机构的统计map key 是机构的code
        Map<String,Map<String, List<ETLModel>>> tjAdminTeamMap = new HashMap<String,Map<String, List<ETLModel>>>();//团队级的统计map 一  key 团队id
        //统计市
       compute(tjCityMap,data.get(3));
        //统计区
       compute(tjTownMap,data.get(2));
       //统计机构
       compute(tjOrgMap,data.get(1));
       //统计团队
       compute(tjAdminTeamMap,data.get(0));
        returnMapsList.add(0,tjAdminTeamMap);
        returnMapsList.add(1,tjOrgMap);
        returnMapsList.add(2,tjTownMap);
        returnMapsList.add(3,tjCityMap);
        return returnMapsList;
    }
    /**
     * 统计算法
     * @param tjMap
     * @param eltDateMap
     */
    private void compute(Map<String, Map<String, List<ETLModel>>> tjMap, Map<String, List<ETLModel>> eltDateMap) throws Exception{
        //遍历数据Map
        for(Map.Entry<String,List<ETLModel>> oneData:eltDateMap.entrySet()){
            List<ETLModel> datas=oneData.getValue();//得到数据列表 全部区或者市或者机构或者区的数据
            Map<String, List<ETLModel>> childrens=new HashMap<String, List<ETLModel>>();//返回的map
            for(ETLModel eltModel:datas){
                Integer age= IdCardUtil.getAgeForIdcard(eltModel.getIdcard());//得到年龄
                String key=getAgeCode(age);//根据年龄得到key
                List<ETLModel> etlModels= childrens.get(key);
                //如果list不存在 新建一个
                if(etlModels==null){
                    etlModels=new ArrayList<>();
                }
                etlModels.add(eltModel);
                childrens.put(key,etlModels);
            }
            tjMap.put(oneData.getKey(),childrens);
        }
    }
    private String getAgeCode(int age) {
        if (age < 7) {
            return Constant.level_age_1;
        } else if (age >= 7 && age < 18) {
            return Constant.level_age_2;
        } else if (age >= 18 && age < 30) {
            return Constant.level_age_3;
        } else if (age >= 30 && age < 50) {
            return Constant.level_age_4;
        } else if (age >= 50 && age < 65) {
            return Constant.level_age_5;
        } else {
            return Constant.level_age_6;
        }
    }
}

+ 0 - 69
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/role/PatientSexRole.java

@ -1,69 +0,0 @@
package com.yihu.wlyy.statistics.etl.role;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016.10.09.
 * 患者性别分组
 */
@Component
@Transactional
public class PatientSexRole {
    public List<Map<String, Map<String, List<ETLModel>>>> elt(List<Map<String, List<ETLModel>>> data) throws  Exception{
        List<Map<String, Map<String, List<ETLModel>>>> returnMapsList=new ArrayList<Map<String, Map<String, List<ETLModel>>>>();
        Map<String,Map<String, List<ETLModel>>> tjCityMap = new HashMap<String,Map<String, List<ETLModel>>>();//市级的统计map key 是区行政区划350200
        Map<String,Map<String, List<ETLModel>>> tjTownMap = new HashMap<String,Map<String, List<ETLModel>>>();//区级的统计map key 是区行政区划350206
        Map<String,Map<String, List<ETLModel>>> tjOrgMap = new HashMap<String,Map<String, List<ETLModel>>>();//机构的统计map key 是机构的code
        Map<String,Map<String, List<ETLModel>>> tjAdminTeamMap = new HashMap<String,Map<String, List<ETLModel>>>();//团队级的统计map 一  key 团队id
        //统计市
        compute(tjCityMap,data.get(3));
        //统计区
        compute(tjTownMap,data.get(2));
        //统计机构
        compute(tjOrgMap,data.get(1));
        //统计团队
        compute(tjAdminTeamMap,data.get(0));
        returnMapsList.add(0,tjAdminTeamMap);
        returnMapsList.add(1,tjOrgMap);
        returnMapsList.add(2,tjTownMap);
        returnMapsList.add(3,tjCityMap);
        return returnMapsList;
    }
    /**
     * 统计算法
     * @param tjMap
     * @param eltDateMap
     */
    private void compute(Map<String, Map<String, List<ETLModel>>> tjMap, Map<String, List<ETLModel>> eltDateMap) throws Exception{
        //遍历数据Map
        for(Map.Entry<String,List<ETLModel>> oneData:eltDateMap.entrySet()){
            List<ETLModel> datas=oneData.getValue();//得到数据列表 全部区或者市或者机构或者区的数据
            Map<String, List<ETLModel>> childrens=new HashMap<String, List<ETLModel>>();//返回的map
            for(ETLModel eltModel:datas){
                String sexKey= IdCardUtil.getSexForIdcard(eltModel.getIdcard());//得到年龄
                List<ETLModel> etlModels= childrens.get(sexKey);
                //如果list不存在 新建一个
                if(etlModels==null){
                    etlModels=new ArrayList<>();
                }
                etlModels.add(eltModel);
                childrens.put(sexKey,etlModels);
            }
            tjMap.put(oneData.getKey(),childrens);
        }
    }
}

+ 211 - 80
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/DBStorage.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.statistics.etl.storage;
import com.mysql.jdbc.Blob;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.TownDao;
@ -7,21 +8,27 @@ import com.yihu.wlyy.statistics.dao.WlyyQuotaResultDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.system.City;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import javax.transaction.TransactionManager;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
/**
@ -30,7 +37,7 @@ import java.util.*;
 */
@Component
@Transactional
@Scope("prototype")
public class DBStorage   {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
@ -44,6 +51,10 @@ public class DBStorage   {
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
@ -76,15 +87,55 @@ public class DBStorage   {
        city.setName(Constant.cityName);
        cityMap.put(Constant.city,city);
        //保存团队
        saveAdminTeamDataLevel1(data.get(0),date,adminTeamMap);
        saveAll(saveAdminTeamDataLevel1(data.get(0),date,adminTeamMap));
        //保存机构
        saveHospitalTeamDataLevel1(data.get(1),date,hospitalsMap);
        saveAll(saveHospitalTeamDataLevel1(data.get(1),date,hospitalsMap));
        //保存区
        saveTownTeamDataLevel1(data.get(2),date,townsMap);
        saveAll(saveTownTeamDataLevel1(data.get(2),date,townsMap));
        //保存市
        saveCityTeamDataLevel1(data.get(3),date,cityMap);
        saveAll(saveCityTeamDataLevel1(data.get(3),date,cityMap));
    }
    /**
            * 保存一级维度的数据
    * @param data
    * @param date
    * @param wlyyQuota
    * @throws Exception
    */
    public List<WlyyQuotaResult> getLevel1(List<Map<String, List<ETLModel>>> data,String date,WlyyQuotaVO wlyyQuota) throws Exception {
        List<WlyyQuotaResult> returnList=new ArrayList<WlyyQuotaResult>();
        this.wlyyQuota=wlyyQuota;
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //全部的市
        Map<String, City> cityMap = new HashMap<String, City>();
        City city=new City();
        city.setCode(Constant.city);
        city.setName(Constant.cityName);
        cityMap.put(Constant.city,city);
        //保存团队
        returnList.addAll(saveAdminTeamDataLevel1(data.get(0),date,adminTeamMap));
        //保存机构
        returnList.addAll(saveHospitalTeamDataLevel1(data.get(1),date,hospitalsMap));
        //保存区
        returnList.addAll(saveTownTeamDataLevel1(data.get(2),date,townsMap));
        //保存市
        returnList.addAll(saveCityTeamDataLevel1(data.get(3),date,cityMap));
        return returnList;
    }
    /**
     * 保存二级维度
     * @param data
@ -98,6 +149,48 @@ public class DBStorage   {
        this.wlyyQuota=wlyyQuota;
        level2Public(data, day, foreachNum, type, start);
    }
    /**
     * 得到二级维度
     * @param data
     * @param day
     * @param wlyyQuota
     * @param foreachNum 如果start是默认的 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param start 起始位置 默认是1
     */
    public List<WlyyQuotaResult> getLevel2(List<Map<String, Map<String, List<ETLModel>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum,Integer type,Integer start)throws Exception {
        List<WlyyQuotaResult> returnList=new ArrayList<WlyyQuotaResult>();
        this.wlyyQuota=wlyyQuota;
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //全部的市
        City city=new City();
        city.setCode(Constant.city);
        city.setName(Constant.cityName);
        Map<String, City> cityMap = new HashMap<String, City>();
        cityMap.put(Constant.city,city);
        //保存团队
        returnList.addAll(saveAdminTeamDataLevel2(data.get(0),day,adminTeamMap,foreachNum,type,start));
        //保存机构
        returnList.addAll(saveHospitalTeamDataLevel2(data.get(1),day,hospitalsMap,foreachNum,type,start));
        //保存区
        returnList.addAll(saveTownTeamDataLevel2(data.get(2),day,townsMap,foreachNum,type,start));
        //保存市
        returnList.addAll(saveCityTeamDataLevel2(data.get(3),day,cityMap,foreachNum,type,start));
        return returnList;
    }
    /**
     * 保存二级维度
     * @param data
@ -118,9 +211,10 @@ public class DBStorage   {
     * @param wlyyQuota
     * @param foreachNum2 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param foreachNum3 标识三级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用
     * @param type2 1性别 2年龄 3用户分组 4.签约费用 5健康服务 6年龄2
     * @param type3 1 疾病分组
     */
    public void saveByLevel3(List<Map<String, Map<String, Map<String, List<ETLModel>>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum2,Integer foreachNum3,Integer type) throws Exception{
    public void saveByLevel3(List<Map<String, Map<String, Map<String, List<ETLModel>>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum2,Integer foreachNum3,Integer type2,Integer type3) throws Exception{
        Integer start2=1;
        Integer start3=1;
        this.wlyyQuota=wlyyQuota;
@ -145,13 +239,13 @@ public class DBStorage   {
        Map<String, City> cityMap = new HashMap<String, City>();
        cityMap.put(Constant.city,city);
        //保存团队
        saveAdminTeamDataLevel3(data.get(0),day,adminTeamMap,foreachNum2,foreachNum3,type,start2,start3);
        saveAdminTeamDataLevel3(data.get(0),day,adminTeamMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存机构
        saveHospitalTeamDataLevel3(data.get(1),day,hospitalsMap,foreachNum2,foreachNum3,type,start2,start3);
        saveHospitalTeamDataLevel3(data.get(1),day,hospitalsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存区
        saveTownTeamDataLevel3(data.get(2),day,townsMap,foreachNum2,foreachNum3,type,start2,start3);
        saveTownTeamDataLevel3(data.get(2),day,townsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存市
        saveCityTeamDataLevel3(data.get(3),day,cityMap,foreachNum2,foreachNum3,type,start2,start3);
        saveCityTeamDataLevel3(data.get(3),day,cityMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
    }
    /**
@ -161,16 +255,17 @@ public class DBStorage   {
     * @param wlyyQuota
     * @param foreachNum2 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param foreachNum3 标识三级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用
     * @param type2 1 性别 2 年龄 3 用户分组 4.签约费用 5健康服务 6年龄2
     * @param type3 1 疾病类型
     * @param start2 耳機維度起始位置 默认是1
     * @param start3 耳機維度起始位置 默认是1
     */
    public void saveByLevel3(List<Map<String, Map<String, Map<String, List<ETLModel>>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum2,Integer foreachNum3,Integer type,Integer start2,Integer start3) throws Exception{
    public void saveByLevel3(List<Map<String, Map<String, Map<String, List<ETLModel>>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum2,Integer foreachNum3,Integer type2,Integer type3,Integer start2,Integer start3) throws Exception{
        if(start2==null){
            start2=1;
        }
        if(start3==null){
            start2=3;
            start2=1;
        }
        this.wlyyQuota=wlyyQuota;
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
@ -194,18 +289,18 @@ public class DBStorage   {
        Map<String, City> cityMap = new HashMap<String, City>();
        cityMap.put(Constant.city,city);
        //保存团队
        saveAdminTeamDataLevel3(data.get(0),day,adminTeamMap,foreachNum2,foreachNum3,type,start2,start3);
        saveAdminTeamDataLevel3(data.get(0),day,adminTeamMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存机构
        saveHospitalTeamDataLevel3(data.get(1),day,hospitalsMap,foreachNum2,foreachNum3,type,start2,start3);
        saveHospitalTeamDataLevel3(data.get(1),day,hospitalsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存区
        saveTownTeamDataLevel3(data.get(2),day,townsMap,foreachNum2,foreachNum3,type,start2,start3);
        saveTownTeamDataLevel3(data.get(2),day,townsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        //保存市
        saveCityTeamDataLevel3(data.get(3),day,cityMap,foreachNum2,foreachNum3,type,start2,start3);
        saveCityTeamDataLevel3(data.get(3),day,cityMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
    }
    private void saveAdminTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, AdminTeam> adminTeamMap, Integer foreachNum2, Integer foreachNum3, Integer type, Integer start2, Integer start3)throws  Exception {
    private void saveAdminTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, AdminTeam> adminTeamMap, Integer foreachNum2, Integer foreachNum3, Integer type2,Integer type3, Integer start2, Integer start3)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,AdminTeam> oneAdminTeam:adminTeamMap.entrySet()){
@ -213,15 +308,17 @@ public class DBStorage   {
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneAdminTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                 //得到每个团队的三级维度
                 Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                 Map<String, List<ETLModel>> threeETLMap=null;
                 if(twoETLMap!=null){
                     threeETLMap=twoETLMap.get(i);
                     threeETLMap=twoETLMap.get(i+"");
                 }
                 for(int j=start3;j<=foreachNum3;j++){
                     int num=0;
                     List<ETLModel> etlModelList= threeETLMap.get(i);
                     if(etlModelList!=null&&etlModelList.size()>0){
                         num=etlModelList.size();
                     if(threeETLMap!=null){
                         List<ETLModel> etlModelList= threeETLMap.get(j+"");
                         if(etlModelList!=null&&etlModelList.size()>0){
                             num=etlModelList.size();
                         }
                     }
                     AdminTeam adminTeamObj = adminTeamMap.get(oneAdminTeam.getKey());//团队
                     if(adminTeamObj==null)continue;
@ -240,14 +337,15 @@ public class DBStorage   {
                     String level="1";
                     String level2=i+"";
                     String level3=j+"";
                     String level3Name=getLevel3Name(level3,type);
                     wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,null,level3,level3Name,day));
                     String level2Name=getLevel2Name(level2,type2);
                     String level3Name=getLevel3Name(level3,type3);
                     wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,level3,level3Name,day));
                }
            }
        }
        saveAll(wlyyQuotaResults);
    }
    private void saveHospitalTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, Hospital> hospitalsMap, Integer foreachNum2, Integer foreachNum3, Integer type, Integer start2, Integer start3) throws  Exception{
    private void saveHospitalTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, Hospital> hospitalsMap, Integer foreachNum2, Integer foreachNum3, Integer type2,Integer type3, Integer start2, Integer start3) throws  Exception{
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,Hospital> oneHospital:hospitalsMap.entrySet()){
@ -257,13 +355,15 @@ public class DBStorage   {
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i);
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    int num=0;
                    List<ETLModel> etlModelList= threeETLMap.get(i);
                    if(etlModelList!=null&&etlModelList.size()>0){
                        num=etlModelList.size();
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    Hospital hospital = hospitalsMap.get(oneHospital.getKey());
                    if(hospital==null)continue;
@ -276,17 +376,18 @@ public class DBStorage   {
                    String doctorCode="";
                    String doctorName="";
                    String doctorJob="";
                    String level="1";
                    String level="2";
                    String level2=i+"";
                    String level3=j+"";
                    String level3Name=getLevel3Name(level3,type);
                   wlyyQuotaResults.add( save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,null,level3,level3Name,day));
                    String level2Name=getLevel2Name(level2,type2);
                    String level3Name=getLevel3Name(level3,type3);
                   wlyyQuotaResults.add( save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,level3,level3Name,day));
                }
            }
        }
        saveAll(wlyyQuotaResults);
    }
    private void saveTownTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, Town> townsMap, Integer foreachNum2, Integer foreachNum3, Integer type, Integer start2, Integer start3) throws  Exception{
    private void saveTownTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, Town> townsMap, Integer foreachNum2, Integer foreachNum3, Integer type2,Integer type3,  Integer start2, Integer start3) throws  Exception{
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,Town> oneTownTeam:townsMap.entrySet()){
@ -296,13 +397,15 @@ public class DBStorage   {
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i);
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    int num=0;
                    List<ETLModel> etlModelList= threeETLMap.get(i);
                    if(etlModelList!=null&&etlModelList.size()>0){
                        num=etlModelList.size();
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    Town townObj=townsMap.get(oneTownTeam.getKey());
                    if(townObj==null)continue;
@ -315,17 +418,18 @@ public class DBStorage   {
                    String doctorCode="";
                    String doctorName="";
                    String doctorJob="";
                    String level="1";
                    String level="3";
                    String level2=i+"";
                    String level3=j+"";
                    String level3Name=getLevel3Name(level3,type);
                   wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,null,level3,level3Name,day));
                    String level2Name=getLevel2Name(level2,type2);
                    String level3Name=getLevel3Name(level3,type3);
                   wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,level3,level3Name,day));
                }
            }
        }
        saveAll((wlyyQuotaResults));
    }
    private void saveCityTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, City> cityMap, Integer foreachNum2, Integer foreachNum3, Integer type, Integer start2, Integer start3) throws  Exception{
    private void saveCityTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String day, Map<String, City> cityMap, Integer foreachNum2, Integer foreachNum3, Integer type2,Integer type3,  Integer start2, Integer start3) throws  Exception{
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,City> oneCityTeam:cityMap.entrySet()){
@ -335,13 +439,15 @@ public class DBStorage   {
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i);
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    int num=0;
                    List<ETLModel> etlModelList= threeETLMap.get(i);
                    if(etlModelList!=null&&etlModelList.size()>0){
                        num=etlModelList.size();
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    String city=Constant.city;
                    String cityName=Constant.cityName;
@ -352,11 +458,12 @@ public class DBStorage   {
                    String doctorCode="";
                    String doctorName="";
                    String doctorJob="";
                    String level="1";
                    String level="4";
                    String level2=i+"";
                    String level3=j+"";
                    String level3Name=getLevel3Name(level3,type);
                    wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,null,level3,level3Name,day));
                    String level2Name=getLevel2Name(level2,type2);
                    String level3Name=getLevel3Name(level3,type3);
                    wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,level3,level3Name,day));
                }
            }
        }
@ -385,16 +492,16 @@ public class DBStorage   {
        Map<String, City> cityMap = new HashMap<String, City>();
        cityMap.put(Constant.city,city);
        //保存团队
        saveAdminTeamDataLevel2(data.get(0),day,adminTeamMap,foreachNum,type,start);
        saveAll( saveAdminTeamDataLevel2(data.get(0),day,adminTeamMap,foreachNum,type,start));
        //保存机构
        saveHospitalTeamDataLevel2(data.get(1),day,hospitalsMap,foreachNum,type,start);
        saveAll( saveHospitalTeamDataLevel2(data.get(1),day,hospitalsMap,foreachNum,type,start));
        //保存区
        saveTownTeamDataLevel2(data.get(2),day,townsMap,foreachNum,type,start);
        saveAll( saveTownTeamDataLevel2(data.get(2),day,townsMap,foreachNum,type,start));
        //保存市
        saveCityTeamDataLevel2(data.get(3),day,cityMap,foreachNum,type,start);
        saveAll( saveCityTeamDataLevel2(data.get(3),day,cityMap,foreachNum,type,start));
    }
    private void saveCityTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, City> citysMap ,Integer foreachNum,Integer type,Integer start) throws  Exception{
    private List<WlyyQuotaResult> saveCityTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, City> citysMap ,Integer foreachNum,Integer type,Integer start) throws  Exception{
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
         for(Map.Entry<String,City> oneCity:citysMap.entrySet()){
             Map<String, List<ETLModel>> oneELTMap= etlModelMap.get(oneCity.getKey());
@ -422,10 +529,10 @@ public class DBStorage   {
                 wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,null,null,day));
             }
         }
        saveAll(wlyyQuotaResults);
        return wlyyQuotaResults;
    }
    private void saveTownTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, Town> townsMap ,Integer foreachNum,Integer type,Integer start)throws  Exception {
    private List<WlyyQuotaResult> saveTownTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, Town> townsMap ,Integer foreachNum,Integer type,Integer start)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String,Town> oneTown:townsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= etlModelMap.get(oneTown.getKey());
@ -453,10 +560,10 @@ public class DBStorage   {
                wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,null,null,day));
            }
        }
        saveAll(wlyyQuotaResults);
        return wlyyQuotaResults;
    }
    private void saveHospitalTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, Hospital> hospitalsMap,Integer foreachNum,Integer type,Integer start)throws  Exception {
    private List<WlyyQuotaResult> saveHospitalTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, Hospital> hospitalsMap,Integer foreachNum,Integer type,Integer start)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String,Hospital> oneHospital:hospitalsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= etlModelMap.get(oneHospital.getKey());
@ -485,10 +592,10 @@ public class DBStorage   {
                wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,null,null,day));
            }
        }
        saveAll(wlyyQuotaResults);
       return wlyyQuotaResults;
    }
    private void saveAdminTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, AdminTeam> adminTeamMap,Integer foreachNum,Integer type,Integer start)throws  Exception {
    private List<WlyyQuotaResult> saveAdminTeamDataLevel2(Map<String, Map<String, List<ETLModel>>> etlModelMap, String day, Map<String, AdminTeam> adminTeamMap,Integer foreachNum,Integer type,Integer start)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String,AdminTeam> adminTeam:adminTeamMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= etlModelMap.get(adminTeam.getKey());
@ -520,10 +627,10 @@ public class DBStorage   {
                wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,level2,level2Name,null,null,day));
            }
        }
        saveAll(wlyyQuotaResults);
       return wlyyQuotaResults;
    }
    private void saveAdminTeamDataLevel1(Map<String, List<ETLModel>> mapData,String date,Map<String, AdminTeam> adminTeamMap)throws  Exception {
    private  List<WlyyQuotaResult>  saveAdminTeamDataLevel1(Map<String, List<ETLModel>> mapData,String date,Map<String, AdminTeam> adminTeamMap)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String, AdminTeam> entry:adminTeamMap.entrySet()){
            List<ETLModel> etlModel= mapData.get(entry.getKey());
@ -548,10 +655,10 @@ public class DBStorage   {
            String level="1";
            wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,null,null,null,null,date));
        }
        saveAll(wlyyQuotaResults);
       return wlyyQuotaResults;
    }
    private void saveHospitalTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date,  Map<String, Hospital> hospitalsMap )throws  Exception {
    private  List<WlyyQuotaResult>  saveHospitalTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date,  Map<String, Hospital> hospitalsMap )throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String, Hospital> entry:hospitalsMap.entrySet()){
            List<ETLModel> etlModel= mapData.get(entry.getKey());
@ -573,10 +680,10 @@ public class DBStorage   {
            String level="2";
            wlyyQuotaResults.add( save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,null,null,null,null,date));
        }
        saveAll(wlyyQuotaResults);
        return wlyyQuotaResults;
    }
    private void saveTownTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date,  Map<String, Town> townsMap)throws  Exception {
    private  List<WlyyQuotaResult>  saveTownTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date,  Map<String, Town> townsMap)throws  Exception {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String, Town> entry:townsMap.entrySet()){
            List<ETLModel> etlModel= mapData.get(entry.getKey());
@ -597,10 +704,10 @@ public class DBStorage   {
            String level="3";
            wlyyQuotaResults.add(save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,null,null,null,null,date));
        }
        saveAll(wlyyQuotaResults);
        return wlyyQuotaResults;
    }
    private void saveCityTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date, Map<String, City> cityMap) throws  Exception{
    private  List<WlyyQuotaResult>  saveCityTeamDataLevel1(Map<String, List<ETLModel>> mapData, String date, Map<String, City> cityMap) throws  Exception{
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        for(Map.Entry<String, City> entry:cityMap.entrySet()){
            List<ETLModel> etlModel= mapData.get(entry.getKey());
@ -621,7 +728,7 @@ public class DBStorage   {
            String level="4";
           wlyyQuotaResults.add( save(num, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level,null,null,null,null,date));
        }
        saveAll(wlyyQuotaResults);
        return wlyyQuotaResults;
    }
    private String getOrg(String org){
@ -647,7 +754,7 @@ public class DBStorage   {
     */
    private WlyyQuotaResult save(int num,  String city, String cityName, String town, String townName, String org, String orgName, String doctorCode, String doctorName, String doctorJob, String level1, String level2, String level2Name,String level3, String level3Name,String date) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setId(UUID.randomUUID().toString().replace("-",""));
        //wlyyQuotaResult.setId(UUID.randomUUID().toString().replace("-",""));
        wlyyQuotaResult.setDel("1");
        wlyyQuotaResult.setOrgCode(org);
        wlyyQuotaResult.setOrgName(orgName);
@ -672,7 +779,9 @@ public class DBStorage   {
        return wlyyQuotaResult;
    }
    private void saveAll(final List<WlyyQuotaResult> wlyyQuotaResults) throws  Exception{
    @Async("dbStorageExecutor")
    @Transactional
    private void saveAll(List<WlyyQuotaResult> wlyyQuotaResults) throws  Exception{
        wlyyQuotaResultDao.save(wlyyQuotaResults);
    }
@ -698,6 +807,11 @@ public class DBStorage   {
                //健康分布
                return Constant.getlevelHealthFbName(i);
            }
            case  6:{
                //年龄2
                return Constant.getLevelAge2(i);
            }
            default:{
                return "";
            }
@ -707,12 +821,29 @@ public class DBStorage   {
    private String getLevel3Name(String j, Integer type) {
        switch (type){
            case  1:{
                //签约费用
                return Constant.getLevelExpenseName(j);
                //疾病类型
                return Constant.getLevelDiseaseName(j);
            }
            default:{
                return "";
            }
        }
    }
    @Transactional
    public void saveLog(final QuartzJobLog quartzJobLog){
       quartzJobLog.setId(UUID.randomUUID().toString().replace("-",""));
       String sql="INSERT INTO wlyy_job_log (id, job_start_time, Job_end_time, job_id, job_content, job_type, job_name) VALUES (?,?,?,?,?,?,?);";
        jdbcTemplate.update(connection -> {
            PreparedStatement statementCreator= connection.prepareCall(sql);
            statementCreator.setString(1,quartzJobLog.getId());
            statementCreator.setTimestamp(2,new Timestamp(quartzJobLog.getJobStartTime().getTime()));
            statementCreator.setTimestamp(3,new Timestamp(quartzJobLog.getJobEndTime().getTime()));
            statementCreator.setString(4,quartzJobLog.getJobId());
            statementCreator.setString(5,quartzJobLog.getJobContent());
            statementCreator.setString(6,quartzJobLog.getJobType());
            statementCreator.setString(7,quartzJobLog.getJobName());
            return statementCreator;
        });
    }
}

+ 942 - 62
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/RedisStorage.java

@ -6,28 +6,37 @@ import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.system.City;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * Created by Administrator on 2016.10.09.
 * 统计数据数据库存储器
 */
@Component
@Transactional
@Scope("prototype")
public class RedisStorage {
    public static String timeKey="";
    public static List<String> keys=new ArrayList<String>();//全部的key
    private Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
    private Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
    private Map<String, Town> townsMap = new HashMap<String, Town>();
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
@ -42,21 +51,22 @@ public class RedisStorage {
     * @param wlyyQuotaId
     * @throws Exception
     */
    public void saveByLevel1(List<Map<String, List<ETLModel>>> data, String wlyyQuotaId) throws Exception {
    public void saveByLevel1(List<Map<String, List<ETLModel>>> data,List<Map<String, List<ETLModel>>> deleteData, String wlyyQuotaId) throws Exception {
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
         Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
@ -71,16 +81,29 @@ public class RedisStorage {
        Map<String, List<ETLModel>> orgTeam=data.get(1);//机构的数据
        Map<String, List<ETLModel>> townTeam=data.get(2);//区的数据
        Map<String, List<ETLModel>> cityTeam=data.get(3);//市的数据
        //保存市
        saveLevel1City(wlyyQuotaId, cityMap, cityTeam);
        //保存区
        saveLevel1Town(wlyyQuotaId, townsMap, townTeam);
        //保存机构
        saveLevel1Org(wlyyQuotaId, hospitalsMap, orgTeam);
        //保存全科团队
        saveLevel1Team(wlyyQuotaId, adminTeamMap, adminTeam);
        if(deleteData==null){
            //保存市
            saveLevel1City(wlyyQuotaId, cityMap, cityTeam);
            //保存区
            saveLevel1Town(wlyyQuotaId, townsMap, townTeam);
            //保存机构
            saveLevel1Org(wlyyQuotaId, hospitalsMap, orgTeam);
            //保存全科团队
            saveLevel1Team(wlyyQuotaId,adminTeamMap, adminTeam);
        }else{
//            //保存市
//            saveLevel1City(wlyyQuotaId, cityMap, cityTeam,deleteData.get(3));
//            //保存区
//            saveLevel1Town(wlyyQuotaId, townsMap, townTeam,deleteData.get(2));
//            //保存机构
//            saveLevel1Org(wlyyQuotaId, hospitalsMap, orgTeam,deleteData.get(1));
//            //保存全科团队
//            saveLevel1Team(wlyyQuotaId,adminTeamMap, adminTeam,deleteData.get(0));
        }
    }
    /**
     * 保存二级维度的数据
     * @param data
@ -88,30 +111,493 @@ public class RedisStorage {
     * @param foreachNum 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     */
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data, String wlyyQuotaId,Integer foreachNum,Integer type) throws Exception {
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data,List<Map<String, Map<String, List<ETLModel>>>> deleteData, String wlyyQuotaId,Integer foreachNum,Integer type) throws Exception {
        Integer start=1;
        saveByLevel2Public(data, wlyyQuotaId, foreachNum, type, start);
        saveByLevel2Public(data,deleteData, wlyyQuotaId, foreachNum, type, start);
    }
    /**
     * 保存二级维度的数据
     * @param data
     * @param wlyyQuotaId
     * @param foreachNum 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param start 循环开始
     */
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data,List<Map<String, Map<String, List<ETLModel>>>> deleteData, String wlyyQuotaId,Integer foreachNum,Integer type,Integer start) throws Exception {
        saveByLevel2Public(data,deleteData, wlyyQuotaId, foreachNum, type, start);
    }
    /**
     * 保存三级维度的数据
     * @param data
     * @param wlyyQuotaId
     * @param foreachNum2 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param foreachNum3 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type2 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param type3 1 疾病
     * @param start2 循环开始
     * @param start3 循环开始
     */
    public void saveByLevel3(List<Map<String, Map<String, Map<String, List<ETLModel>>>>> data,List<Map<String, Map<String, Map<String, List<ETLModel>>>>> deleteData, String wlyyQuotaId,Integer foreachNum2,Integer foreachNum3,Integer type2,Integer type3,Integer start2,Integer start3) throws Exception {
        if(start2==null){
            start2=1;
        }
        if(start3==null){
            start2=1;
        }
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //全部的市
        City city=new City();
        city.setCode(Constant.city);
        city.setName(Constant.cityName);
        Map<String, City> cityMap = new HashMap<String, City>();
        cityMap.put(Constant.city,city);
        if(deleteData!=null){
            //保存团队
            saveAdminTeamDataLevel3(data.get(0),deleteData.get(0),wlyyQuotaId,adminTeamMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存机构
            saveHospitalTeamDataLevel3(data.get(1),deleteData.get(1),wlyyQuotaId,hospitalsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存区
            saveTownTeamDataLevel3(data.get(2),deleteData.get(2),wlyyQuotaId,townsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存市
            saveCityTeamDataLevel3(data.get(3),deleteData.get(3),wlyyQuotaId,cityMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        }else{
            //保存团队
            saveAdminTeamDataLevel3(data.get(0),wlyyQuotaId,adminTeamMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存机构
            saveHospitalTeamDataLevel3(data.get(1),wlyyQuotaId,hospitalsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存区
            saveTownTeamDataLevel3(data.get(2),wlyyQuotaId,townsMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
            //保存市
            saveCityTeamDataLevel3(data.get(3),wlyyQuotaId,cityMap,foreachNum2,foreachNum3,type2,type3,start2,start3);
        }
    }
    private void saveAdminTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,Map<String, Map<String, Map<String, List<ETLModel>>>> deleteEtlModelMap, String wlyyQuotaId,Map<String, AdminTeam> adminTeamMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        //遍历团队的Map
        for(Map.Entry<String,AdminTeam> oneAdminTeam:adminTeamMap.entrySet()){
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneAdminTeam.getKey());
            Map<String, Map<String, List<ETLModel>>> deleteTwoETLMap= deleteEtlModelMap.get(oneAdminTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap=null;
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                Map<String, List<ETLModel>> deleteThreeETLMap=null;
                if(deleteTwoETLMap!=null){
                    deleteThreeETLMap=deleteTwoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level1="1";
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(deleteThreeETLMap!=null){
                        List<ETLModel> etlModelList= deleteThreeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=num-etlModelList.size();
                        }
                    }
                    AdminTeam adminTeamObj = adminTeamMap.get(oneAdminTeam.getKey());//团队
                    if(adminTeamObj==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", adminTeamObj.getName());
                    jo.put("code", adminTeamObj.getId());
                    jo.put("name", getLevel3Name(level3,type3));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+level2+":"+level3+":"+adminTeamObj.getId()).toString(), jo.toString());
                }
            }
        }
    }
    private void saveAdminTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap, String wlyyQuotaId,Map<String, AdminTeam> adminTeamMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        //遍历团队的Map
        for(Map.Entry<String,AdminTeam> oneAdminTeam:adminTeamMap.entrySet()){
            JSONArray level2Jr=new JSONArray();
            AdminTeam adminTeamObj = adminTeamMap.get(oneAdminTeam.getKey());//团队
            String level1="1";
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneAdminTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                JSONArray jrlevel2=new JSONArray();
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap=null;
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(adminTeamObj==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", getLevel3Name(level3,type3));
                    jo.put("code", level3);
                    StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+adminTeamObj.getId()+":"+level2+":"+":"+level3+":"+timeKey);
                    keys.add(sb.toString());
                    redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                    level2Jr.put(jo);
                    jrlevel2.put(jo);
                }
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+adminTeamObj.getId()+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jrlevel2.toString());
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+adminTeamObj.getId()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), level2Jr.toString());
        }
    }
    private String getLevel3Name(String j, Integer type) {
        switch (type){
            case  1:{
                //疾病类型
                return Constant.getLevelDiseaseName(j);
            }
            default:{
                return "";
            }
        }
    }
    private void saveHospitalTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,Map<String, Map<String, Map<String, List<ETLModel>>>> deleteEtlModelMap,String wlyyQuotaId, Map<String, Hospital> hospitalMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        //遍历团队的Map
        for(Map.Entry<String,Hospital> oneHospital:hospitalMap.entrySet()){
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneHospital.getKey());
            Map<String, Map<String, List<ETLModel>>> deleteTwoETLMap= deleteEtlModelMap.get(oneHospital.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                Map<String, List<ETLModel>> deleteThreeETLMap= new HashMap<String, List<ETLModel>>();
                if(deleteTwoETLMap!=null){
                    deleteThreeETLMap=deleteTwoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level1="2";
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(deleteThreeETLMap!=null&&deleteThreeETLMap.size()>0){
                        List<ETLModel> etlModelList= deleteThreeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=num-etlModelList.size();
                        }
                    }
                    Hospital hospital = hospitalsMap.get(oneHospital.getKey());
                    if(hospital==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", hospital.getName());
                    jo.put("code", hospital.getCode());
                    jo.put("name", getLevel3Name(level3,type3));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+level2+":"+level3+":"+hospital.getCode()).toString(), jo.toString());
                }
            }
        }
    }
    private void saveHospitalTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,String wlyyQuotaId, Map<String, Hospital> hospitalMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        Map<String,Map<String,JSONArray>> cityJr=new HashMap<String,Map<String,JSONArray>>();
        //遍历团队的Map
        for(Map.Entry<String,Hospital> oneHospital:hospitalMap.entrySet()){
            Hospital hospital = hospitalsMap.get(oneHospital.getKey());
            if(hospital==null)continue;
            JSONArray jr=new JSONArray();
            String level1="2";
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneHospital.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                JSONArray jrlevel2=new JSONArray();
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(hospital==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", getLevel3Name(level3,type3));
                    jo.put("code", level3);
                    StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+":"+hospital.getCode()+":"+level2+":"+level3+":"+timeKey);
                    keys.add(sb.toString());
                    redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                    jr.put(jo);
                    jrlevel2.put(jo);
                }
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+hospital.getCode()+":"+i+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jrlevel2.toString());
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+hospital.getCode()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), jr.toString());
        }
    }
    private void saveTownTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,Map<String, Map<String, Map<String, List<ETLModel>>>> deleteEtlModelMap,String wlyyQuotaId, Map<String, Town> townsMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,Town> oneTownTeam:townsMap.entrySet()){
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneTownTeam.getKey());
            Map<String, Map<String, List<ETLModel>>> deleteTwoETLMap= deleteEtlModelMap.get(oneTownTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                Map<String, List<ETLModel>> deleteThreeETLMap= new HashMap<String, List<ETLModel>>();
                if(deleteTwoETLMap!=null){
                    deleteThreeETLMap=deleteTwoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level1="3";
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(deleteThreeETLMap!=null&&deleteThreeETLMap.size()>0){
                        List<ETLModel> etlModelList= deleteThreeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=num-etlModelList.size();
                        }
                    }
                    Town town=townsMap.get(oneTownTeam.getKey());
                    if(town==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", town.getName());
                    jo.put("code", town.getCode());
                    jo.put("name", getLevel3Name(level3,type3));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+level2+":"+level3+":"+town.getCode()).toString(), jo.toString());
                }
            }
        }
    }
    private void saveCityTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,Map<String, Map<String, Map<String, List<ETLModel>>>> deleteEtlModelMap,String wlyyQuotaId, Map<String, City> cityMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        List<WlyyQuotaResult> wlyyQuotaResults=new ArrayList<WlyyQuotaResult>();
        //遍历团队的Map
        for(Map.Entry<String,City> oneCityTeam:cityMap.entrySet()){
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneCityTeam.getKey());
            Map<String, Map<String, List<ETLModel>>> deleteTwoETLMap= deleteEtlModelMap.get(oneCityTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                Map<String, List<ETLModel>> deletetThreeETLMap= new HashMap<String, List<ETLModel>>();
                if(deleteTwoETLMap!=null){
                    deletetThreeETLMap=deleteTwoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level1="4";
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(deletetThreeETLMap!=null&&deletetThreeETLMap.size()>0){
                        List<ETLModel> etlModelList= deletetThreeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=num-etlModelList.size();
                        }
                    }
                    City cityObj=oneCityTeam.getValue();
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name", cityObj.getName());
                    jo.put("code", cityObj.getCode());
                    jo.put("name", getLevel3Name(level3,type3));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+level2+":"+level3+":"+cityObj.getCode()).toString(), jo.toString());
                }
            }
        }
    }
    private void saveTownTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,String wlyyQuotaId, Map<String, Town> townsMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        //遍历团队的Map
        for(Map.Entry<String,Town> oneTownTeam:townsMap.entrySet()){
            Town town=townsMap.get(oneTownTeam.getKey());
            JSONArray jr=new JSONArray();
            String level1="3";
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneTownTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                JSONArray jrlevel2=new JSONArray();
                //得到每个团队的三级维度
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    if(town==null)continue;
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    //jo.put("name", town.getName());
                    //jo.put("code", town.getCode());
                    jo.put("level2code", level2);
                    jo.put("level2name", getLevel2Name(level2,type2));
                    jo.put("name", getLevel3Name(level3,type3));
                    jo.put("code",level3 );
                    StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+town.getCode()+":"+level2+":"+level3+":"+timeKey);
                    keys.add(sb.toString());
                    redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                    jr.put(jo);
                    jrlevel2.put(jo);
                }
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+town.getCode()+":"+i+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jrlevel2.toString());
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+town.getCode()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), jr.toString());
        }
    }
    private void saveCityTeamDataLevel3(Map<String, Map<String, Map<String, List<ETLModel>>>> etlModelMap,String wlyyQuotaId, Map<String, City> cityMap, Integer foreachNum2, Integer foreachNum3, Integer type2, Integer type3, Integer start2, Integer start3) {
        //遍历团队的Map
        for(Map.Entry<String,City> oneCityTeam:cityMap.entrySet()){
            City cityObj=oneCityTeam.getValue();
            JSONArray jr=new JSONArray();
            String level1="4";
            //得到每个团队的2级维度
            Map<String, Map<String, List<ETLModel>>> twoETLMap= etlModelMap.get(oneCityTeam.getKey());
            for(int i=start2;i<=foreachNum2;i++){
                //得到每个团队的三级维度
                JSONArray jrLevel2=new JSONArray();
                Map<String, List<ETLModel>> threeETLMap= new HashMap<String, List<ETLModel>>();
                if(twoETLMap!=null){
                    threeETLMap=twoETLMap.get(i+"");
                }
                for(int j=start3;j<=foreachNum3;j++){
                    String level2=i+"";
                    String level3=j+"";
                    int num=0;
                    if(threeETLMap!=null&&threeETLMap.size()>0){
                        List<ETLModel> etlModelList= threeETLMap.get(j+"");
                        if(etlModelList!=null&&etlModelList.size()>0){
                            num=etlModelList.size();
                        }
                    }
                    JSONObject jo=new JSONObject();
                    jo.put("date", DateUtil.dateToStrLong(new Date()));
                    jo.put("num", num);
                    jo.put("name",getLevel3Name(level3,type3));
                    jo.put("code",level3);
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data, String wlyyQuotaId,Integer foreachNum,Integer type,Integer start) throws Exception {
        saveByLevel2Public(data, wlyyQuotaId, foreachNum, type, start);
                    StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+cityObj.getCode()+":"+level2+":"+level3+":"+timeKey);
                    keys.add(sb.toString());
                    redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                    jrLevel2.put(jo);
                    jr.put(jo);
                }
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+cityObj.getCode()+":"+i+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jrLevel2.toString());
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":"+level1+":"+cityObj.getCode()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), jr.toString());
        }
    }
    private void saveByLevel2Public(List<Map<String, Map<String, List<ETLModel>>>> data, String wlyyQuotaId, Integer foreachNum, Integer type, Integer start) {
    private void saveByLevel2Public(List<Map<String, Map<String, List<ETLModel>>>> data,List<Map<String, Map<String, List<ETLModel>>>> deleteData, String wlyyQuotaId, Integer foreachNum, Integer type, Integer start) {
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
         townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
@ -126,19 +612,32 @@ public class RedisStorage {
        Map<String, Map<String, List<ETLModel>>> orgTeam=data.get(1);//机构的数据
        Map<String, Map<String, List<ETLModel>>> townTeam=data.get(2);//区的数据
        Map<String, Map<String, List<ETLModel>>> cityTeam=data.get(3);//市的数据
        //保存市
        saveLevel2City(wlyyQuotaId, cityMap, cityTeam,foreachNum,type,start);
        //保存区
        saveLevel2Town(wlyyQuotaId, townsMap, townTeam,foreachNum,type,start);
        //保存机构
        saveLevel2Org(wlyyQuotaId, hospitalsMap, orgTeam,foreachNum,type,start);
        //保存全科团队
        saveLevel2Team(wlyyQuotaId, adminTeamMap, adminTeam,foreachNum,type,start);
        if(deleteData!=null){
//            //保存市
//            saveLevel2City(wlyyQuotaId, cityMap, cityTeam,deleteData.get(3),foreachNum,type,start);
//            //保存区
//            saveLevel2Town(wlyyQuotaId, townsMap, townTeam,deleteData.get(2),foreachNum,type,start);
//            //保存机构
//            saveLevel2Org(wlyyQuotaId, hospitalsMap, orgTeam,deleteData.get(1),foreachNum,type,start);
//            //保存全科团队
//            saveLevel2Team(wlyyQuotaId, adminTeamMap, adminTeam,deleteData.get(0),foreachNum,type,start);
        }else{
            //保存市
            saveLevel2City(wlyyQuotaId, cityMap, cityTeam,foreachNum,type,start);
            //保存区
            saveLevel2Town(wlyyQuotaId, townsMap, townTeam,foreachNum,type,start);
            //保存机构
            saveLevel2Org(wlyyQuotaId, hospitalsMap, orgTeam,foreachNum,type,start);
            //保存全科团队
            saveLevel2Team(wlyyQuotaId, adminTeamMap, adminTeam,foreachNum,type,start);
        }
    }
    private void saveLevel2Team(String wlyyQuotaId, Map<String, AdminTeam> adminTeamMap, Map<String, Map<String, List<ETLModel>>> eltModel, Integer foreachNum, Integer type,Integer start) {
    private void saveLevel2Team(String wlyyQuotaId, Map<String, AdminTeam> adminTeamMap, Map<String, Map<String, List<ETLModel>>> eltModel, Map<String, Map<String, List<ETLModel>>> deleteEltModel, Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,AdminTeam> adminTeam:adminTeamMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(adminTeam.getKey());
            Map<String, List<ETLModel>> deleteOneELTMap= deleteEltModel.get(adminTeam.getKey());
            for(int i=start;i<=foreachNum;i++){
                AdminTeam adminTeamObj=adminTeam.getValue();
                if(adminTeamObj==null)continue;
@ -150,20 +649,58 @@ public class RedisStorage {
                        num=etlModel.size();
                    }
                }
                if(deleteOneELTMap!=null){
                    List<ETLModel> etlModel1= deleteOneELTMap.get(i+"");
                    if(etlModel1!=null&&etlModel1.size()>0){
                        num=num-etlModel1.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                jo.put("teamName", adminTeamObj.getName());
                jo.put("teamId", adminTeamObj.getId());
                jo.put("name", adminTeamObj.getName());
                jo.put("code", adminTeamObj.getId());
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":1:"+key+":"+adminTeam.getKey()).toString(), jo.toString());
            }
        }
    }
    private void saveLevel2Team(String wlyyQuotaId, Map<String, AdminTeam> adminTeamMap, Map<String, Map<String, List<ETLModel>>> eltModel,  Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,AdminTeam> adminTeam:adminTeamMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(adminTeam.getKey());
            JSONArray level2=new JSONArray();
            for(int i=start;i<=foreachNum;i++){
                AdminTeam adminTeamObj=adminTeam.getValue();
                if(adminTeamObj==null)continue;
                JSONObject jo=new JSONObject();
                int num=0;
                if(oneELTMap!=null){
                    List<ETLModel> etlModel= oneELTMap.get(i+"");
                    if(etlModel!=null&&etlModel.size()>0){
                        num=etlModel.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                jo.put("code",key);
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":1:"+adminTeam.getKey().toString()+":"+key+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jo.toString());
    private void saveLevel2Org(String wlyyQuotaId, Map<String, Hospital> hospitalsMap, Map<String, Map<String, List<ETLModel>>> eltModel, Integer foreachNum, Integer type,Integer start) {
                level2.put(jo);
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":1:"+adminTeam.getKey().toString()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), level2.toString());
        }
    }
    private void saveLevel2Org(String wlyyQuotaId, Map<String, Hospital> hospitalsMap, Map<String, Map<String, List<ETLModel>>> eltModel, Map<String, Map<String, List<ETLModel>>> deleteEltModel, Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,Hospital> hospital:hospitalsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(hospital.getKey());
            Map<String, List<ETLModel>> deleteOneELTMap= deleteEltModel.get(hospital.getKey());
            for(int i=start;i<=foreachNum;i++){
                Hospital hospitalObj=hospital.getValue();
                if(hospitalObj==null)continue;
@ -175,20 +712,89 @@ public class RedisStorage {
                        num=etlModel.size();
                    }
                }
                if(deleteOneELTMap!=null){
                    List<ETLModel> etlModel1= deleteOneELTMap.get(i+"");
                    if(etlModel1!=null&&etlModel1.size()>0){
                        num=num-etlModel1.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                jo.put("orgName", hospitalObj.getName());
                jo.put("orgCode", hospitalObj.getCode());
                jo.put("name", hospitalObj.getName());
                jo.put("code", hospitalObj.getCode());
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":2:"+key+":"+hospital.getKey()).toString(), jo.toString());
            }
        }
    }
    private void saveLevel2Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, Map<String, List<ETLModel>>> eltModel,  Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,Town> town:townsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(town.getKey());
            JSONArray level2=new JSONArray();
            for(int i=start;i<=foreachNum;i++){
                JSONObject jo=new JSONObject();
                int num=0;
                if(oneELTMap!=null){
                    List<ETLModel> etlModel= oneELTMap.get(i+"");
                    if(etlModel!=null&&etlModel.size()>0){
                        num=etlModel.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                jo.put("code",key);
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":3:"+town.getKey()+":"+key+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                level2.put(jo);
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":3:"+town.getKey()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), level2.toString());
        }
    }
    private void saveLevel2Org(String wlyyQuotaId, Map<String, Hospital> hospitalsMap, Map<String, Map<String, List<ETLModel>>> eltModel,Integer foreachNum, Integer type,Integer start) {
        Map<String,Map<String,JSONArray>> townjr=new HashMap<String,Map<String,JSONArray>>();
        for(Map.Entry<String,Hospital> hospital:hospitalsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(hospital.getKey());
            JSONArray level2=new JSONArray();
            for(int i=start;i<=foreachNum;i++){
                Hospital hospitalObj=hospital.getValue();
                if(hospitalObj==null)continue;
                JSONObject jo=new JSONObject();
                int num=0;
                if(oneELTMap!=null){
                    List<ETLModel> etlModel= oneELTMap.get(i+"");
                    if(etlModel!=null&&etlModel.size()>0){
                        num=etlModel.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                jo.put("code",key);
                addJOLeval2(townjr,hospitalObj.getTown(),key,jo);
                level2.put(jo);
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":2:"+hospital.getKey().toString()+":"+key+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jo.toString());
    private void saveLevel2Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, Map<String, List<ETLModel>>> eltModel, Integer foreachNum, Integer type,Integer start) {
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":2:"+hospital.getKey().toString()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), level2.toString());
        }
    }
    private void saveLevel2Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, Map<String, List<ETLModel>>> eltModel, Map<String, Map<String, List<ETLModel>>> deleteEltModel, Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,Town> town:townsMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(town.getKey());
            Map<String, List<ETLModel>> deleteOneELTMap= deleteEltModel.get(town.getKey());
            for(int i=1;i<=foreachNum;i++){
                JSONObject jo=new JSONObject();
                int num=0;
@ -198,10 +804,16 @@ public class RedisStorage {
                        num=etlModel.size();
                    }
                }
                if(deleteOneELTMap!=null){
                    List<ETLModel> etlModel1= deleteOneELTMap.get(i+"");
                    if(etlModel1!=null&&etlModel1.size()>0){
                        num=num-etlModel1.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                jo.put("townName", town.getValue().getName());
                jo.put("townCode", town.getValue().getCode());
                jo.put("name", town.getValue().getName());
                jo.put("code", town.getValue().getCode());
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":3:"+key+":"+town.getKey()).toString(), jo.toString());
@ -209,9 +821,10 @@ public class RedisStorage {
        }
    }
    private void saveLevel2City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, Map<String, List<ETLModel>>> eltModel, Integer foreachNum, Integer type,Integer start) {
    private void saveLevel2City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, Map<String, List<ETLModel>>> eltModel, Map<String, Map<String, List<ETLModel>>> deleteEltModel, Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,City> city:cityMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(city.getKey());
            Map<String, List<ETLModel>> deleteOneELTMap= deleteEltModel.get(city.getKey());
            for(int i=start;i<=foreachNum;i++){
                JSONObject jo=new JSONObject();
                int num=0;
@ -221,18 +834,56 @@ public class RedisStorage {
                        num=etlModel.size();
                    }
                }
                if(deleteOneELTMap!=null){
                    List<ETLModel> etlModel1= deleteOneELTMap.get(i+"");
                    if(etlModel1!=null&&etlModel1.size()>0){
                        num=num-etlModel1.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                jo.put("cityName", city.getValue().getName());
                jo.put("cityCode", city.getValue().getCode());
                jo.put("name", city.getValue().getName());
                jo.put("code", city.getValue().getCode());
                String key=i+"";
                jo.put("name", getLevel2Name(key,type));
                jo.put("name", getLevel2Name(key,type));
                redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":4:"+key+":"+city.getKey()).toString(), jo.toString());
            }
        }
    }
    private void saveLevel2City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, Map<String, List<ETLModel>>> eltModel,  Integer foreachNum, Integer type,Integer start) {
        for(Map.Entry<String,City> city:cityMap.entrySet()){
            Map<String, List<ETLModel>> oneELTMap= eltModel.get(city.getKey());
            JSONArray level2=new JSONArray();
            for(int i=start;i<=foreachNum;i++){
                JSONObject jo=new JSONObject();
                int num=0;
                if(oneELTMap!=null){
                    List<ETLModel> etlModel= oneELTMap.get(i+"");
                    if(etlModel!=null&&etlModel.size()>0){
                        num=etlModel.size();
                    }
                }
                jo.put("date", DateUtil.dateToStrLong(new Date()));
                jo.put("num", num);
                String key=i+"";
                jo.put("code", key);
                jo.put("name", getLevel2Name(key,type));
                StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":4:"+city.getKey()+":"+key+":"+timeKey);
                keys.add(sb.toString());
                redisTemplate.opsForValue().set(sb.toString(), jo.toString());
                level2.put(jo);
            }
            StringBuffer sb=new StringBuffer("quota:"+wlyyQuotaId+":4:"+city.getKey()+":"+timeKey);
            keys.add(sb.toString());
            redisTemplate.opsForValue().set(sb.toString(), level2.toString());
        }
    }
    private void saveLevel1Team(String wlyyQuotaId, Map<String, AdminTeam> adminTeamMap, Map<String, List<ETLModel>> adminTeam) {
        JSONArray cityjr=new JSONArray();
        Map<String,JSONArray> townjr=new HashMap<String,JSONArray>();//key是town
        Map<String,JSONArray> orgjr=new HashMap<String,JSONArray>();//key是机构
        for(Map.Entry<String,AdminTeam> entry:adminTeamMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
@ -244,13 +895,66 @@ public class RedisStorage {
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("teamName", adminTeamObj.getName());
            jo.put("teamId", adminTeamObj.getId());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":1:"+entry.getKey()).toString(), jo.toString());
            jo.put("name", adminTeamObj.getName());
            jo.put("code", adminTeamObj.getId()+"");
            String orgKey=adminTeamObj.getOrgCode();
            Hospital hospital=hospitalsMap.get(orgKey);
            if(hospital==null)continue;
            String townKey=hospital.getTown();
            cityjr.put(jo);
            addJO(townjr,townKey,jo);
            addJO(orgjr,orgKey,jo);
            StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":1:"+entry.getKey()+":"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), jo.toString());
        }
    }
        //保存市下面全部的团队
        StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":4:"+Constant.city+":1:"+timeKey);
        keys.add(key.toString());
        redisTemplate.opsForValue().set(key.toString(), cityjr.toString());
        //保存区下面全部的团队
        for(Map.Entry<String,JSONArray> entry:townjr.entrySet()){
            key=new StringBuffer("quota:"+wlyyQuotaId+":3:"+entry.getKey()+":1:"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), entry.getValue().toString());
        }
        //保存机构下面全部的团队
        for(Map.Entry<String,JSONArray> entry:orgjr.entrySet()){
            key=new StringBuffer("quota:"+wlyyQuotaId+":2:"+entry.getKey()+":1:"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), entry.getValue().toString());
        }
    }
    private void saveLevel1Team(String wlyyQuotaId, Map<String, AdminTeam> adminTeamMap, Map<String, List<ETLModel>> adminTeam, Map<String, List<ETLModel>> deleteAdminTeam) {
        for(Map.Entry<String,AdminTeam> entry:adminTeamMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
            AdminTeam adminTeamObj=entry.getValue();
            if(adminTeamObj==null)continue;
            List<ETLModel> etlList=adminTeam.get(entry.getKey());
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            if(deleteAdminTeam!=null&&deleteAdminTeam.size()>0){
                List<ETLModel> deleteEtlList=deleteAdminTeam.get(entry.getKey());
                if(deleteEtlList!=null&&deleteEtlList.size()>0){
                    num=num-deleteEtlList.size();
                }
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("name", adminTeamObj.getName());
            jo.put("code", adminTeamObj.getId());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":1:"+entry.getKey()).toString()+":0", jo.toString());
        }
    }
    private void saveLevel1Org(String wlyyQuotaId, Map<String, Hospital> hospitalsMap, Map<String, List<ETLModel>> orgTeam) {
        JSONArray cityjr=new JSONArray();
        Map<String,JSONArray> townjr=new HashMap<String,JSONArray>();
        for(Map.Entry<String,Hospital> entry:hospitalsMap.entrySet()){
            Hospital hospital=entry.getValue();
            if(hospital==null)continue;
@ -262,13 +966,114 @@ public class RedisStorage {
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("orgName", hospital.getName());
            jo.put("orgCode", hospital.getCode());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":2:"+entry.getKey()).toString(), jo.toString());
            jo.put("name", hospital.getName());
            jo.put("code", hospital.getCode());
            cityjr.put(jo);
            String townKey=hospital.getTown();
            addJO(townjr, townKey, jo);
            StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":2:"+entry.getKey()+":"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), jo.toString());
        }
        //保存市下面全部的机构
        StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":4:"+Constant.city+":2:"+timeKey);
        keys.add(key.toString());
        redisTemplate.opsForValue().set(key.toString(), cityjr.toString());
        //保存区下面全部的机构
        for(Map.Entry<String,JSONArray> entry:townjr.entrySet()){
            key=new StringBuffer("quota:"+wlyyQuotaId+":3:"+entry.getKey()+":2:"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), entry.getValue().toString());
        }
    }
    private void saveLevel1Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, List<ETLModel>> townTeam) {
    private void addJO(Map<String, JSONArray> townjr,String key, JSONObject jo) {
        if(townjr.containsKey(key)){
            townjr.get(key).put(jo);
        }else{
            JSONArray townjrList=new JSONArray();
            townjrList.put(jo);
            townjr.put(key,townjrList);
        }
    }
    private void addJOLeval2(Map<String,Map<String, JSONArray>> townjr,String key1,String key2, JSONObject jo) {
        if(townjr.containsKey(key1)){
            Map<String, JSONArray> level2=townjr.get(key1);
            if(level2.containsKey(key2)){
                JSONArray jr=level2.get(key2);
                jr.put(jo);
            }else{
                JSONArray jr=new JSONArray();
                jr.put(jo);
                level2.put(key2,jr);
            }
        }else{
            Map<String, JSONArray> level2=new HashMap<>();
            JSONArray jr=new JSONArray();
            jr.put(jo);
            level2.put(key2,jr);
            townjr.put(key1,level2);
        }
    }
    private void addJOLeval3(Map<String,Map<String, Map<String, JSONArray>>> townjr,String key1,String key2,String key3, JSONObject jo) {
        if(townjr.containsKey(key1)){
            Map<String, Map<String, JSONArray>> level1= townjr.get(key1);
            if(level1.containsKey(key2)){
                Map<String, JSONArray> level2=level1.get(key2);
                if(level2.containsKey(key3)){
                    JSONArray jr=level2.get(key3);
                    jr.put(jo);
                }else{
                    JSONArray jr=new JSONArray();
                    jr.put(jo);
                    level2.put(key3,jr);
                }
            }else{
                Map<String, JSONArray> level2=new HashMap<>();
                JSONArray jr=new JSONArray();
                jr.put(jo);
                level2.put(key3,jr);
                level1.put(key2,level2);
            }
        }else{
            Map<String, Map<String, JSONArray>> level1=new HashMap<>();
            Map<String, JSONArray> level2=new HashMap<>();
            JSONArray level3=new JSONArray();
            level3.put(jo);
        }
    }
    private void saveLevel1Org(String wlyyQuotaId, Map<String, Hospital> hospitalsMap, Map<String, List<ETLModel>> orgTeam, Map<String, List<ETLModel>> deleteOrgTeam) {
        for(Map.Entry<String,Hospital> entry:hospitalsMap.entrySet()){
            Hospital hospital=entry.getValue();
            if(hospital==null)continue;
            JSONObject jo=new JSONObject();
            Integer num=0;
            List<ETLModel> etlList=orgTeam.get(entry.getKey());
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            if(deleteOrgTeam!=null&&deleteOrgTeam.size()>0){
                List<ETLModel> deleteEtlList=deleteOrgTeam.get(entry.getKey());
                if(deleteEtlList!=null&&deleteEtlList.size()>0){
                    num=num-deleteEtlList.size();
                }
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("name", hospital.getName());
            jo.put("code", hospital.getCode());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":2:"+entry.getKey()).toString()+":0", jo.toString());
        }
    }
    private void saveLevel1Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, List<ETLModel>> townTeam, Map<String, List<ETLModel>> deleteTownTeam) {
        for(Map.Entry<String,Town> entry:townsMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
@ -276,15 +1081,44 @@ public class RedisStorage {
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            if(deleteTownTeam!=null&&deleteTownTeam.size()>0){
                List<ETLModel> deleteEtlList=deleteTownTeam.get(entry.getKey());
                if(deleteEtlList!=null&&deleteEtlList.size()>0){
                    num=num-deleteEtlList.size();
                }
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("townName", entry.getValue().getName());
            jo.put("townCode", entry.getValue().getCode());
            jo.put("name", entry.getValue().getName());
            jo.put("code", entry.getValue().getCode());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":3:"+entry.getKey()).toString(), jo.toString());
        }
    }
    private void saveLevel1City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, List<ETLModel>> cityTeam) {
    private void saveLevel1Town(String wlyyQuotaId, Map<String, Town> townsMap, Map<String, List<ETLModel>> townTeam) {
        JSONArray jr=new JSONArray();
        for(Map.Entry<String,Town> entry:townsMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
            List<ETLModel> etlList=townTeam.get(entry.getKey());
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("name", entry.getValue().getName());
            jo.put("code", entry.getValue().getCode());
            jr.put(jo);
            StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":3:"+entry.getKey()+":"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), jo.toString());
        }
        //保存市下面全部的区
        StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":4:"+Constant.city+":3:"+timeKey);
        keys.add(key.toString());
        redisTemplate.opsForValue().set(key.toString(), jr.toString());
    }
    private void saveLevel1City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, List<ETLModel>> cityTeam, Map<String, List<ETLModel>> deleteCityTeam) {
        JSONArray jr=new JSONArray();
        for(Map.Entry<String,City> entry:cityMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
@ -292,14 +1126,40 @@ public class RedisStorage {
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            if(deleteCityTeam!=null&&deleteCityTeam.size()>0){
            List<ETLModel> deleteEtlList=deleteCityTeam.get(entry.getKey());
                if(deleteEtlList!=null&&deleteEtlList.size()>0){
                    num=num-deleteEtlList.size();
                }
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("cityName", entry.getValue().getName());
            jo.put("cityCode", entry.getValue().getCode());
            redisTemplate.opsForValue().set(new StringBuffer("quota:"+wlyyQuotaId+":4:"+entry.getKey()).toString(), jo.toString());
            jo.put("name", entry.getValue().getName());
            jo.put("code", entry.getValue().getCode());
            jr.put(jo);
        }
        StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":4:"+Constant.city+":");
        keys.add(key.toString());
        redisTemplate.opsForValue().set(key.toString(), jr.toString());
    }
    private void saveLevel1City(String wlyyQuotaId, Map<String, City> cityMap, Map<String, List<ETLModel>> cityTeam) {
        for(Map.Entry<String,City> entry:cityMap.entrySet()){
            JSONObject jo=new JSONObject();
            Integer num=0;
            List<ETLModel> etlList=cityTeam.get(entry.getKey());
            if(etlList!=null&&etlList.size()>0){
                num=etlList.size();
            }
            jo.put("date", DateUtil.dateToStrLong(new Date()));
            jo.put("num", num);
            jo.put("name", entry.getValue().getName());
            jo.put("code", entry.getValue().getCode());
            StringBuffer key=new StringBuffer("quota:"+wlyyQuotaId+":4:"+Constant.city+":"+timeKey);
            keys.add(key.toString());
            redisTemplate.opsForValue().set(key.toString(), jo.toString());
        }
    }
    private String getLevel2Name(String i, Integer type) {
        switch (type){
            case  1:{
@ -314,9 +1174,29 @@ public class RedisStorage {
                //用户分组
                return Constant.getLevelGroupName(i);
            }
            case  4:{
                //疾病
                return Constant.getLevelDiseaseName(i);
            }
            case  5:{
                //疾病
                return Constant.getlevelHealthFbName(i);
            }
            case  6:{
                //疾病
                return Constant.getLevelExpenseName(i);
            }
            default:{
                return "";
            }
        }
    }
    private String getOrg(String org){
        //if(!"00".equals(org.substring(org.length()-2,org.length()))){
        if(org.length() == 10 && !org.endsWith("00")){
            return org.substring(0,org.length()-2)+"00";
        }else{
            return org;
        }
    }
}

+ 51 - 154
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AllSignExpenseStatusJob.java

@ -1,21 +1,23 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.Level2Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonDateValueProcessor;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
@ -26,6 +28,7 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * Created by Administrator on 2016.10.11.
@ -33,27 +36,24 @@ import java.util.*;
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class AllSignExpenseStatusJob implements Job{
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String date; //起始时间
@ -70,6 +70,7 @@ public class AllSignExpenseStatusJob implements Job{
            //计算指标
            computequota();
        }catch (Exception e){
            e.printStackTrace();
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
@ -79,150 +80,46 @@ public class AllSignExpenseStatusJob implements Job{
    /**
     * 计算指标
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + date + "' and quato_code='" + 14 + "'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams = doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId() + "", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的已改簽信息
        String dateTemp = date + " 17:30:00 ";
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterday(dateTemp);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount = new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount = new Long(0L);//脏数据
        Boolean isAll = true;//是否统计失败
        StringBuffer errorContent = new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels = new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for (SignFamily signFamily : signFamilys) {
            ETLModel etlModel = new ETLModel();
            String orgCode = signFamily.getHospital();
            if (StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:" + signFamily.getCode() + ",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll = false;
                errorCount++;
                continue;
            }
            String orgCodeTemp = "";
            if (!"00".equals(orgCode.substring(orgCode.length() - 2, orgCode.length()))) {
                //站
                orgCodeTemp = orgCode.substring(0, orgCode.length() - 2) + "00";
            } else {
                //社区
                orgCodeTemp = orgCode;
            }
            //判断社区有没有值
            Hospital hospital = hospitalsMap.get(orgCodeTemp);
            if (hospital == null) {
                errorContent.append("签约code:" + signFamily.getCode() + ",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll = false;
                errorCount++;
                continue;
            }
            Long adminId = signFamily.getAdminTeamId();
            if (adminId == null || adminId <= 0) {
                errorContent.append("签约code:" + signFamily.getCode() + ",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll = false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(signFamily.getAdminTeamId() + "");
            if (adminTeam == null) {
                errorContent.append("签约code:" + signFamily.getCode() + ",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll = false;
                errorCount++;
                continue;
            }
            String idCard = signFamily.getIdcard();
            if (idCard == null || (idCard.length() != 18 && idCard.length() != 15)) {
                errorContent.append("签约code:" + signFamily.getCode() + ",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll = false;
                errorCount++;
                continue;
            }
            String town = hospital.getTown();
            if (StringUtils.isEmpty(town)) {
                errorContent.append("签约code:" + signFamily.getCode() + ",机构表的中的town为空");
                isAll = false;
                errorCount++;
                continue;
            }
            Town townObj = townsMap.get(town);
            if (townObj == null) {
                errorContent.append("签约code:" + signFamily.getCode() + ",机构表的中的town不存在");
                isAll = false;
                errorCount++;
                continue;
            }
            etlModel.setLevel2Key(signFamily.getExpensesStatus());//设置二级维度的Key
            etlModel.setAdminTeam(adminTeam.getId() + "");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
    private void computequota()throws Exception {
        try {
            deleteData();
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存中取数据到已经缴费的数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(date);
            List<SignFamily> signFamilies_1=cacheModel.getSignFamilies();
            //抽取第二种条件的语句
            String sql=" select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"' and (expenses_status !=1 or expenses_status is null)";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2  and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            List<SignFamily> signFamilies_2= dbExtract.extractByPage(SignFamily.class,sql,sqlCount,true);
            //抽取的语句
            sql="select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'";
            signFamilies_2.addAll(signFamilies_1);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies_2, SignDataFilter.level2Expenses,sql,date);
            //统计数据
            List<Map<String, List<ETLModel>>> returnDatas = levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);
            //保存数据
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= level2Role.elt(returnDatas);
            //数据转换
            dbStorage.saveByLevel2(level2Data,date,wlyyQuota,2,4,0);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            dbStorage.saveLog(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
            errorContent.append("统计失败:" + e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys, adminCount, orgCount, townCount, cityCount, isAll, errorContent, errorCount));
        quartzJobLog.setJobType(isAll ? "1" : "0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount) {
        StringBuffer string = new StringBuffer("统计" + date + " 的簽約数据完成 ,数据库查询到簽約数据:" + signFamilys.size());
        string.append(",过滤的脏数据数目:" + errorCount);
        string.append(",统计到市的数据总数:" + cityCount);
        string.append(",统计到区的数据总数:" + townCount);
        string.append(",统计到机构的数据总数:" + orgCount);
        string.append(",统计到团队的数据总数:" + qkCount);
        string.append(",是否统计成功:" + isAll);
        if (!isAll) {
            string.append(",失败原因:" + errorContent);
        }
        return string.toString();
    @Transactional
    private void deleteData() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + date + "' and quato_code='" + 14 + "'");
    }
    public String getYesterday() {

+ 37 - 152
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AllSignJob.java

@ -1,20 +1,19 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
@ -25,6 +24,7 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * Created by Administrator on 2016.10.10.
@ -32,25 +32,22 @@ import java.util.*;
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class AllSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String date; //起始时间
@ -76,150 +73,38 @@ public class AllSignJob implements Job {
    /**
     * 计算指标
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+date+"' and quato_code='"+13+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的已改簽信息
        String dateTemp=date+" 17:30:00 ";
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(dateTemp);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||(idCard.length()!=18&&idCard.length()!=15)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            deleteData();
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(date);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),cacheModel.getSql(),date);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnData= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,date,wlyyQuota);
            dbStorage.saveByLevel1(returnData,date,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            dbStorage.saveLog(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+date+" 的簽約数据完成 ,数据库查询到簽約数据:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    @Transactional
    private void deleteData() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+date+"' and quato_code='"+13+"'");
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);

+ 35 - 148
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ChangeSignJob.java

@ -1,7 +1,10 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
@ -9,14 +12,14 @@ import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
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 org.springframework.transaction.annotation.Transactional;
@ -25,34 +28,33 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 已改簽的指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class ChangeSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    String yesterday; //起始时间
    String now;//结束时间
    String daybefore;//结束时间
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
@ -63,8 +65,8 @@ public class ChangeSignJob implements Job {
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();//前天
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();//昨天
            //计算指标
            computequota();
        }catch (Exception e){
@ -73,151 +75,36 @@ public class ChangeSignJob implements Job {
            e2.setRefireImmediately(true);
        }
    }
    /**
     * 计算指标
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+10+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的已改簽信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingChaangeSignYesterdayExpensesStatus(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+10+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的已改簽信息
            String sql=" select code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and a.status =100 and  a.patient_apply_date< '"+yesterday+ Constant.quota_date_last+"' and a.expenses_status=1 ";
            //抽取數據
            List<SignFamily> signFamilies= dbExtract.extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的已改簽数据完成 ,数据库查询到改签数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    public String getYesterday() {

+ 32 - 3
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/Constant.java

@ -5,6 +5,7 @@ package com.yihu.wlyy.statistics.job.business;
 * 常量类
 */
public class Constant {
    public static String quota_date_last=" 17:00:00 ";
    public static String city="350200";
    public static String cityName="厦门市";
    //二级维度的性别
@ -29,27 +30,37 @@ public class Constant {
    public static String level_age_5_name="51~65";
    public static String level_age_6_name=">65";
    //二级维度的年龄
    public static String level_age2_1="1";
    public static String level_age2_2="2";
    public static String level_age2_1_name="<=65";
    public static String level_age2_2_name=">65";
    //二级维度的组
    public static String level_group_0="0";
    public static String level_group_1="1";
    public static String level_group_2="2";
    public static String level_group_3="3";
    public static String level_group_4="4";
    public static String level_group_5="5";
    public static String level_group_6="6";
    public static String level_group_7="7";
    public static String level_group_0_name="未分組";
    public static String level_group_1_name="普通人群";
    public static String level_group_2_name="慢病人群";
    public static String level_group_2_name="慢病65岁以下人群";
    public static String level_group_3_name="65岁以上人群";
    public static String level_group_4_name="高血压";
    public static String level_group_5_name="糖尿病";
    public static String level_group_6_name="糖尿病和高血压";
    public static String level_group_7_name="慢病65岁以上人群";
    //二级维度签约扣费
    public static String level_expense_0="0";
    public static String level_expense_1="1";
    public static String level_expense_2="2";
    public static String level_expense_0_name="未扣费";
    public static String level_expense_1_name="已扣费";
    public static String level_expense_0_name="未缴费人数";
    public static String level_expense_1_name="已缴费人数";
    public static String level_expense_2_name="已退费";
    //二级维度健康分布
@ -95,6 +106,18 @@ public class Constant {
        return "";
    }
    public static String getLevelAge2(String key){
        switch (key){
            case "1":{
                return level_age2_1_name;
            }
            case "2":{
                return level_age2_2_name;
            }
        }
        return "";
    }
    public static String getLevelExpenseName(String key){
        switch (key){
            case "1":{
@ -125,6 +148,9 @@ public class Constant {
    }
    public static String getLevelGroupName(String key){
        switch (key){
            case "0":{
                return level_group_0_name;
            }
            case "1":{
                return level_group_1_name;
            }
@ -143,6 +169,9 @@ public class Constant {
            case "6":{
                return level_group_6_name;
            }
            case "7":{
                return level_group_7_name;
            }
        }
        return "";
    }

+ 36 - 120
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ConsultJob.java

@ -1,22 +1,26 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.ConsultDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
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 org.springframework.transaction.annotation.Transactional;
@ -25,12 +29,14 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 咨询模块的指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class ConsultJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
@ -38,22 +44,18 @@ public class ConsultJob implements Job {
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private ConsultDataFilter consultDataFilter;
    @Autowired
    private DBExtract dbExtract;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
@ -65,7 +67,7 @@ public class ConsultJob implements Job {
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();  //線刪除今天的数据
            //计算指标
            computequota();
@ -77,123 +79,37 @@ public class ConsultJob implements Job {
    }
    @Transactional
    private void computequota() {
        try{
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+3+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //找出全部的团队
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的咨询信息
        List<ConsultTeam> consultTeams = consultTeamDao.findByCzrqyYesterday(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(ConsultTeam consultTeam:consultTeams){
            ETLModel etlModel=new ETLModel();
            Long adminId=consultTeam.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",咨询的团队(wlyy_consult_team)中的admin_team_code数据为空");
                isAll=false;
                continue;
            }
            String teamCode = consultTeam.getAdminTeamId()+"";//行政的团队的id
            AdminTeam adminTeam=adminTeamMap.get(teamCode);
            if(adminTeam == null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",团队Id:"+adminTeam.getId()+",咨询的团队(wlyy_consult_team)中的团队不存在");
                isAll=false;
                continue;
            }
            String orgCode = adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",团队Id:"+adminTeam.getId()+",医生团队的机构为空");
                isAll=false;
                continue;
            }
            String orgCodeTemp="";
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            //统计区 ---------------start--------------
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id,医生团队的机构不存在");
                isAll=false;
                continue;
            }
            String town=hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id:"+hospital.getId()+",机构表的区字段(town)为空");
                isAll=false;
                continue;
            }
            Town townObj=townsMap.get(town);
            if(townObj==null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id:"+hospital.getId()+",机构表的区不存在");
                isAll=false;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            String sql=" select admin_team_code,id from wlyy_consult_team a where a.type=2 and a.czrq>='"+daybefore+ Constant.quota_date_last+"' and a.czrq< '"+yesterday+ Constant.quota_date_last+"'";
            //抽取數據
            List<ConsultTeam> consultTeams= dbExtract.extract(ConsultTeam.class,sql);
            //過濾數據
            FilterModel etlModels= consultDataFilter.filter(consultTeams,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(consultTeams,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<ConsultTeam> consultTeams, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
    private String saveContent(List<ConsultTeam> consultTeams, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的咨询数据完成 ,数据库查询到咨询数目:"+consultTeams.size());
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);

+ 269 - 1355
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentDayAllQuotaJob.java

@ -1,11 +1,17 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.ConsultDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.FollowUpDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.HealthGuideDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.*;
import com.yihu.wlyy.statistics.etl.storage.RedisStorage;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
@ -16,8 +22,11 @@ import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
@ -25,61 +34,42 @@ 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.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 * 实时统计今天的数据
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class CurrentDayAllQuotaJob implements Job {
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private PatientHealthGuidanceDao patientHealthGuidanceDao;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private PatientAgeRole patientAgeRole;
    @Autowired
    private PatientSexRole patientSexRole;
    private ConsultDataFilter consultDataFilter;
    @Autowired
    private RedisStorage redisStorage;
    private HealthGuideDataFilter healthGuideDataFilter;
    @Autowired
    private SignPatientLabelInfoDao signPatientLabelInfoDao;
    private FollowUpDataFilter followUpDataFilter;
    private org.apache.tomcat.jdbc.pool.DataSource fvdataSource = new org.apache.tomcat.jdbc.pool.DataSource();//随访数据源
    private JdbcTemplate jdbcTemplate = new JdbcTemplate();
    private JdbcTemplate fv_jdbcTemplate = new JdbcTemplate();
    List<Town> towns = null;//厦门市全部的区
    List<Hospital> hospitals = null;//系统全部的机构
@ -88,11 +78,15 @@ public class CurrentDayAllQuotaJob implements Job {
    Map<String, Town> townsMap = new HashMap<String, Town>();
    Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
    private String now = getDayString(0);
    private String now = getDayString(-1)+ Constant.quota_date_last;
    private String tomorrow = getDayString(1);
    private StringBuffer allContent=new StringBuffer();//日志内容
    private  StringBuffer errorContent=new StringBuffer();//日常内容
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${fv.jdbc.driver}")
    String fv_jdbc_driver;
    @Value("${fv.jdbc.url}")
@ -111,7 +105,7 @@ public class CurrentDayAllQuotaJob implements Job {
            fvdataSource.setUsername(fv_jdbc_username);
            fvdataSource.setPassword(fv_jdbc_password);
            jdbcTemplate.setDataSource(fvdataSource);//初始化随访的数据源
            fv_jdbcTemplate.setDataSource(fvdataSource);//初始化随访的数据源
            towns = townDao.findByCityCode(Constant.city); //查找出厦门市全部的区
            hospitals = hospitalDao.findHospitalzxFWZ(); //查找出系统全部的机构
            adminTeams=doctorAdminTeamDao.findAllTeam();//查找出系统全部的全科医生
@ -124,386 +118,178 @@ public class CurrentDayAllQuotaJob implements Job {
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //清空缓存
            CachePool.cleanAllCache();
            //计算指标
            computequota();
        }catch (Exception e){
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }
    //统计
    private void computequota() throws Exception {
        RedisStorage.timeKey=new Date().getTime()+"";
        QuartzJobLog quartzJobLog =new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        allContent=new StringBuffer();
        computequota_1(); //统计今天的签约
        //找出今天的签约信息 yesterday,now
        String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status,patient from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
        String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
        //抽取數據
        List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
        computequota_1(sql,signFamilies,null); //统计今天的签约
        computequota_2(); //统计今天的解约
        computequota_3(); //统计今天的健康咨询量
        computequota_4(); //统计今天的随访量
        computequota_5(); //统计今天的健康指导
        computequota_6(); //统计今天的签约患者性别
        computequota_7();//统计今天的签约患者分组
        computequota_8();//统计今天的签约患者年龄
        computequota_6(sql,signFamilies,null); //统计今天的签约患者性别
        computequota_7(sql,signFamilies,null);//统计今天的签约患者分组
        computequota_8(sql,signFamilies,null);//统计今天的签约患者年龄
        computequota_9();//统计今天的待签约
        computequota_10();//统计今天的改签
        computequota_12();//统计今天的签约下按年龄分组后再
        computequota_15();//统计健康分布统计
        computequota_12(sql,signFamilies,null);//统计今天的签约下按年龄分组后再
        computequota_13(sql,signFamilies,null);//统计今天的签约量
        computequota_16_1(sql,signFamilies,null);//统计今天的签约数的扣费钱 1
        computequota_15(sql,signFamilies,null);//统计今天的健康分布统计
        //computequota_16_0(sql,signFamilies,null);//统计今天的签约数的未扣费 0
        quartzJobLog.setJobContent(allContent.toString());
        quartzJobLog.setJobName("实时统计");
        quartzJobLog.setJobId("11");
        quartzJobLog.setJobType("1");
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLogDao.save(quartzJobLog);
    }
        for (String key :RedisStorage.keys){
            redisTemplate.expire(key, 1, TimeUnit.HOURS);//1小时过期
        }
        RedisStorage.keys.clear();//清空Key
    private void computequota_15() {
        errorContent=new StringBuffer();
        String quotaId="15";
        //找出今天的签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now, tomorrow);
        //更新统计时间
        redisTemplate.opsForValue().set("quota:date",DateUtil.dateToStrLong(new Date()));
        //更新时间key
        redisTemplate.opsForValue().set("quota:timeKey",RedisStorage.timeKey);
    }
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            //查找每个患者的健康分布标签
            List<SignPatientLabelInfo> signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"2",1);
            String level2Key="0";
            if(signPatientLabelInfoList!=null&&signPatientLabelInfoList.size()>0){
                level2Key=signPatientLabelInfoList.get(0).getLabel();
            }
            etlModel.setLevel2Key(level2Key);//设置二级维度的Key
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
    private void computequota_16_1(String sql,List<SignFamily> signFamilies_1,List<SignFamily> deleteSignFamilies) {
        String quotaId="16";
        try{
            sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and (expenses_status !=1 or expenses_status is null) and status in (1,2) and    a.apply_date< '"+tomorrow+"' ";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and (expenses_status !=1 or expenses_status is null) and status in (1,2) and  a.apply_date< '"+tomorrow+"' ";
            List<SignFamily> signFamilies_2= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
            signFamilies_2.addAll(signFamilies_1);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies_2, SignDataFilter.level2Expenses,sql,null);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存redis
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,2,6,0);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        //数据过滤清洗出脏数据  -----------end
        allContent.append("-----------16-1----------");
    }
    private void computequota_13(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        //找出今天的签约信息 yesterday,now
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>> roleData= level2Role.elt(returnData1s);
           //抽取數據 分页抽取
           //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
           //统计数据
           List<Map<String, List<ETLModel>>>  returnData= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel2(roleData,quotaId,4,1,0);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnData,null,"13");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------15----------");
        allContent.append("-----------13----------");
    }
    private void computequota_12() throws Exception{
         errorContent=new StringBuffer();
    private void computequota_16_0(String sql,List<SignFamily> signFamilies_1,List<SignFamily> deleteSignFamilies) {
        String quotaId="16";
        //找出今天的签约信息
        try{
            //抽取第二种条件的语句 找出未缴费的
            sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and (expenses_status =0 or expenses_status is null) and    a.apply_date< '"+tomorrow+"' ";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and (expenses_status =0 or expenses_status is null)  and  a.apply_date< '"+tomorrow+"' ";
            List<SignFamily> signFamilies_2= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
             //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies_2, SignDataFilter.level2Expenses,sql,null);
            //统计数据
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,0,4,0);
        //找出今天的签约信息 yesterday,now
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------16-0----------");
    }
    private void computequota_15(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        String quotaId="15";
        //找出今天的签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now, tomorrow);
        //数组里面第一个是健康人群 第二个是慢病人群 第三个是65岁以上人群
        Map<String, Map<String, Map>> cityAgeMap = new HashMap<String, Map<String, Map>>();//key是市行政代码 目前只有厦门市
        Map<String,Map> temp =new HashMap<String,Map>();
        cityAgeMap.put(Constant.city, temp);
        //String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
       try{
           //抽取數據
          // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies, SignDataFilter.level2Health,sql,null);
           //统计数据 一级维度
           List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
           //统计数据 二级维度
           List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(patientSexRoleData,null,quotaId,4,5,0);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------15----------");
    }
        Map<String, Map<String, Map>> townAgeMap = new HashMap<String, Map<String, Map>>();//key是区行政代码
        Map<String, Map<String, Map>> orgAgeMap = new HashMap<String, Map<String, Map>>();//key是机构代码
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有签约的
        for (SignFamily signFamily : signFamilys) {
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
             town = hospital.getTown();
            int age = IdCardUtil.getAgeForIdcard(signFamily.getIdcard());//根据card解析年龄
            String ageCode = getAgeCode(age);//得到年龄的code
    private void computequota_12(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) throws Exception{
        String quotaId="12";
        //找出今天的签约信息
        //String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
        //String deleteSql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.czrq>= '"+now+"' and  a.czrq< '"+tomorrow+"' and a.expenses_status=3  ";
            boolean hasGXY = false;//有高血压
            boolean hasTNB = false;//有糖尿病
            //如果是慢病的 统计高血压的 糖尿病  1高血压,2糖尿病  糖尿病和高血压是3
            String diseaseType="";
            String jsonString = redisTemplate.opsForValue().get("disease:" + signFamily.getPatient());
            if (StringUtils.isEmpty(jsonString)) {
                diseaseType="4";//健康人群
            }else{
                //排除数据 只留下高血压和糖尿病
                List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
                JSONArray redisValues = new JSONArray(jsonString);
                if(redisValues.length()>0){
                    for (Object obj : redisValues) {
                        JSONObject redisValue =  (JSONObject)(obj);
                        if(!redisValue.has("signType")){
                            continue;
                        }
                        //排除掉三师签约
                        if ("1".equals(redisValue.getString("signType"))) {
                            continue;
                        }
                        String disease = redisValue.getString("disease");
                        if (("1").equals(disease)) {
                            jsonObjects.add(redisValue);
                            hasGXY = true;//设置有高血压
                            diseaseType="1";
                        }
                        if (("2").equals(disease)) {
                            jsonObjects.add(redisValue);
                            hasTNB = true;//设置有糖尿病
                            diseaseType="2";
                        }
                    }
                    if(hasGXY&&hasTNB){
                        diseaseType="3";
                    }
                }else{
                    diseaseType="4";
                }
            }
            //统计市
            compute(cityAgeMap, Constant.city, ageCode, diseaseType);
            //统计区
            compute(townAgeMap, town, ageCode, diseaseType);
            //统计机构
            //统计站
             orgCode=hospital.getCode();
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                 orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                //统计机构
                compute(orgAgeMap, orgCodeTemp, ageCode, diseaseType);
            } else {
                compute(orgAgeMap, hospital.getCode(), ageCode, diseaseType);
            }
        try{
             //抽取數據
           // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Age,SignDataFilter.level3Disease,sql,null);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //统计数据 三级维度
            List<Map<String, Map<String, Map<String, List<ETLModel>>>>> returnD= SpringUtil.getBean(Level3Role.class).elt(patientSexRoleData);
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel3(returnD,null,quotaId,6,4,2,1,1,1);
        }catch (Exception e){
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //保存市级数据
        for (Map.Entry<String, Map<String, Map>> entry : cityAgeMap.entrySet()) {
            Map<String, Map> oneAgeMap = entry.getValue();
            for(int i=1;i<7;i++){
                for(int j=1;j<5;j++){
                    String key_2=i+"";
                    String key_3=j+"";
                    String name=Constant.cityName;
                    JSONObject jsonObject=new JSONObject();
                    if (oneAgeMap != null && oneAgeMap.containsKey(key_2)) {
                        Map<String,Long> key3Map=oneAgeMap.get(key_2);
                        if(key3Map!=null&&key3Map.containsKey(key_3)){
                            jsonObject.put("num",key3Map.get(key_3) + "");
                        }else{
                            jsonObject.put("num",0);
                        }
                    } else {
                        jsonObject.put("num",0);
                    }
                    jsonObject.put("name",name);
                    jsonObject.put("date", DateUtil.dateToStrLong(new Date()));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:12:4:"+i+":"+j+":"+entry.getKey()).toString(),jsonObject.toString());
                }
            }
        }
        //保存区级
        for (Map.Entry<String, Town> entry : townsMap.entrySet()) {
            //判断该区是否有统计数据
            Map<String, Map> oneAgeMap = townAgeMap.get(entry.getKey());//得到当个区的统计数据
            Town townObj = entry.getValue();//得到区级信息
            for(int i=1;i<7;i++){
                for(int j=1;j<5;j++){
                    String key_2=i+"";
                    String key_3=j+"";
                    String name=townObj.getName();
                    JSONObject jsonObject=new JSONObject();
                    if (oneAgeMap != null && oneAgeMap.containsKey(key_2)) {
                        Map<String,Long> key3Map=oneAgeMap.get(key_2);
                        if(key3Map!=null&&key3Map.containsKey(key_3)){
                            jsonObject.put("num",(key3Map.get(key_3) + ""));
                        }else{
                            jsonObject.put("num",0);
                        }
                    } else {
                        jsonObject.put("num",0);
                    }
                    jsonObject.put("name",townObj.getName());
                    jsonObject.put("date", DateUtil.dateToStrLong(new Date()));//quota:12:2:6:1:350200
                    redisTemplate.opsForValue().set(new StringBuffer("quota:12:3:"+i+":"+j+":"+entry.getKey()).toString(),jsonObject.toString());
                }
            }
        }
        //保存机构级
        for (Map.Entry<String, Hospital> entry : hospitalsMap.entrySet()) {
            //判断该机构是否有统计数据
            Map<String, Map> oneAgeMap = orgAgeMap.get(entry.getKey());//得到当个机构的统计数据
            Hospital hospital = entry.getValue();//得到机构信息
            for(int i=1;i<7;i++){
                for(int j=1;j<5;j++){
                    String key_2=i+"";
                    String key_3=j+"";
                    String name=hospital.getName();
                    JSONObject jsonObject=new JSONObject();
                    if (oneAgeMap != null && oneAgeMap.containsKey(key_2)) {
                        Map<String,Long> key3Map=oneAgeMap.get(key_2);
                        if(key3Map!=null&&key3Map.containsKey(key_3)){
                            jsonObject.put("num",(key3Map.get(key_3) + ""));
                        }else{
                            jsonObject.put("num",0);
                        }
                    } else {
                        jsonObject.put("num",0);
                    }
                    jsonObject.put("name",name);
                    jsonObject.put("date", DateUtil.dateToStrLong(new Date()));
                    redisTemplate.opsForValue().set(new StringBuffer("quota:12:2:"+i+":"+j+":"+entry.getKey()).toString(),jsonObject.toString());
                }
            }
        }
        allContent.append( saveContent("12",signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------12----------");
    }
    private void compute(Map<String, Map<String, Map>> rootMap, String rootKey, String ageCode, String diseaseType) {
@ -535,1071 +321,214 @@ public class CurrentDayAllQuotaJob implements Job {
            rootMap.put(rootKey, groupMapTemp2);
        }
    }
    private void computequota_1() {
         errorContent=new StringBuffer();
        //找出今天的签约信息 yesterday,now
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now, tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
    private void computequota_1(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        try{
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,"now");
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,"1");
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,"1");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent("1",signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------1----------");
    }
    private void computequota_2() {
         errorContent=new StringBuffer();
        String quotaId="2";
        //找出今天的解约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||(idCard.length()!=18&&idCard.length()!=15)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //找出今天的解约信息
            String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and a.status in(-3,-4) and  a.apply_unsign_date< '"+tomorrow+"' ";
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("----------2-----------");
         allContent.append("----------2-----------");
    }
    private void computequota_3() {
         errorContent=new StringBuffer();
        String quotaId="3";
        //找出今天的咨询信息
        List<ConsultTeam> consultTeams = consultTeamDao.findByCzrqyYesterday(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(ConsultTeam consultTeam:consultTeams){
            ETLModel etlModel=new ETLModel();
            Long adminId=consultTeam.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",咨询的团队(wlyy_consult_team)中的admin_team_code数据为空");
                isAll=false;
                continue;
            }
            String teamCode = consultTeam.getAdminTeamId()+"";//行政的团队的id
            AdminTeam adminTeam=adminTeamMap.get(teamCode);
            if(adminTeam == null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",团队Id:"+adminTeam.getId()+",咨询的团队(wlyy_consult_team)中的团队不存在");
                isAll=false;
                continue;
            }
            String orgCode = adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",团队Id:"+adminTeam.getId()+",医生团队的机构为空");
                isAll=false;
                continue;
            }
            String orgCodeTemp="";
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            //统计区 ---------------start--------------
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id:"+hospital.getId()+",医生团队的机构不存在");
                isAll=false;
                continue;
            }
            String town=hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id:"+hospital.getId()+",机构表的区字段(town)为空");
                isAll=false;
                continue;
            }
            Town townObj=townsMap.get(town);
            if(townObj==null) {
                errorContent.append("咨询Id:"+consultTeam.getId()+",机构Id:"+hospital.getId()+",机构表的区不存在");
                isAll=false;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //找出今天的咨询信息
            String sql=" select * from wlyy_consult_team a where a.type=2  and a.czrq>= '"+now+"'and a.czrq< '"+tomorrow+"'";
            //抽取數據
            List<ConsultTeam> consultTeams= SpringUtil.getBean(DBExtract.class).extract(ConsultTeam.class,sql);
            //過濾數據
            FilterModel etlModels= consultDataFilter.filter(consultTeams,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,consultTeams.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("----------3-----------");
         allContent.append("----------3-----------");
    }
    private void computequota_4() {
         errorContent=new StringBuffer();
        String quotaId="4";
        //找出今天的随访信息
        List<Map<String,Object>> plans = getFvYesterday();
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(Map<String,Object> plan:plans){
            ETLModel etlModel=new ETLModel();
            Object idCard=plan.get("id_card");//得到隨訪的身份證
            if(StringUtils.isEmpty(idCard)){
                errorContent.append("随访id:"+plan.get("id")+",随访(fv_plan)表id_card为空");
                isAll=false;
                continue;
            }
            SignFamily signFamily=signFamilyDao.findByIdcard(idCard.toString());
            if(signFamily==null){
                errorContent.append("随访id:"+plan.get("id")+",签约code:"+signFamily.getCode()+",随访中的患者身份证在签约表中找不到数据");
                isAll=false;
                continue;
            }
            Long adminTeamId=signFamily.getAdminTeamId();
            if(adminTeamId==null||adminTeamId<=0){
                errorContent.append("随访id:"+plan.get("id")+",签约code:"+signFamily.getCode()+" 中的adminTeamId为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId());
            if(adminTeam==null){
                errorContent.append("随访id:"+plan.get("id")+",签约code:"+signFamily.getCode()+",医生团队不存在");
                isAll=false;
                continue;
            }
            //统计机构------------------start ------------------
            //判断医生属于哪个机构
            String orgCodeTemp="";
            String orgCode=adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("随访id:"+plan.get("id")+",团队Id:"+adminTeam.getId()+",随访的医生所属的团队(wlyy_admin_team)机构为空");
                isAll=false;
                continue;
            }
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital==null){
                errorContent.append("随访id:"+plan.get("id")+",团队Id:"+adminTeam.getId()+",随访的医生所属的团队的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("随访id:"+plan.get("id")+",机构Id:"+hospital.getId()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("随访id:"+plan.get("id")+",机构Id:"+hospital.getId()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            //找出今天的随访信息
            String sql=" select * from fv_plan a where  a.update_time< '"+tomorrow+"' and a.update_time>= '"+now+"' ";
            //找出今天的随访信息
            List<Map<String, Object>> plans = fv_jdbcTemplate.queryForList(sql);
            FilterModel etlModels = followUpDataFilter.filter(plans, sql, null);
            // 统计数据
            List<Map<String, List<ETLModel>>> returnDatas = SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,plans.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------4----------");
            allContent.append("统计失败:"+e.getMessage());
        }allContent.append("-----------4----------");
    }
    private void computequota_5() {
         errorContent=new StringBuffer();
        String quotaId="5";
        List<PatientHealthGuidance> patientHealthGuidances = patientHealthGuidanceDao.findByCzrqyYesterday(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(PatientHealthGuidance patientHealthGuidance:patientHealthGuidances){
            ETLModel etlModel=new ETLModel();
            String patient=patientHealthGuidance.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",患者code:"+patient+",家庭签约不存在");
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamId()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的团队AdminTeamCode为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的团队不存在");
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的机构Hospital不存在");
                isAll=false;
                continue;
            }
            String orgCodeTemp="";
            //统计机构 -----------------start---------------------
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+orgCodeTemp+",健康咨询的医生所属的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+hospital.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+hospital.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        String sql="SELECT * FROM wlyy_patient_health_guidance a WHERE a.czrq< '"+tomorrow+"' and a.czrq>= '"+now+"'";
        try{
            //抽取數據
            List<PatientHealthGuidance> consultTeams= SpringUtil.getBean(DBExtract.class).extract(PatientHealthGuidance.class,sql);
            //過濾數據
            FilterModel etlModels= healthGuideDataFilter.filter(consultTeams,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,patientHealthGuidances.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------5----------");
    }
    private void computequota_6() throws Exception {
        errorContent=new StringBuffer();
    private void computequota_6(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) throws Exception {
        String quotaId="6";
        //找出今天的签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now, tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= patientSexRole.elt(returnData1s);
      //  String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
       try{
           //抽取數據
           //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Sex,sql,null);
           //统计数据 1级维度
           List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
           //统计数据 二级维度
           List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);;
            //保存数据
            redisStorage.saveByLevel2(patientSexRoleData,quotaId,3,1);
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,3,1);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------6----------");
    }
    private void computequota_7() {
        errorContent=new StringBuffer();
    private void computequota_7(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        String quotaId="7";
        String now = getDayString(0);
        String tomorrow = getDayString(1);
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的解约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingUnSignYesterdayExpensesStatus(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            //得到患者的分组标签
            List<SignPatientLabelInfo> signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"1",1);
            String level2Key="1";
            if(signPatientLabelInfoList!=null&&signPatientLabelInfoList.size()>0){
                level2Key=signPatientLabelInfoList.get(0).getLabel();
            }
            etlModel.setLevel2Key(level2Key);//设置二级维度的Key
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            if("2".equals(level2Key)){
                level2Key="0";
                boolean hasGXY=false;//有高血压
                boolean hasTNB=false;//糖尿病
                //得到患者的疾病标签
                signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"3",1);
                for (SignPatientLabelInfo signPatientLabelInfo:signPatientLabelInfoList){
                    if("1".equals(signPatientLabelInfo.getLabel())){
                        level2Key="4";
                        hasGXY=true;
                    }
                    if("2".equals(signPatientLabelInfo.getLabel())){
                        level2Key="5";
                        hasTNB=true;
                    }
                }
                if (hasTNB&&hasGXY){
                    level2Key="6";
                }
                etlModel=new ETLModel();
                etlModel.setLevel2Key(level2Key);//设置二级维度的Key
                etlModel.setAdminTeam(adminTeam.getId()+"");
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
            }
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);
          //  String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
            //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Group,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据 1 表示:从1开始循环 6表示:循环6次 3表示 2级维度是 3
            redisStorage.saveByLevel2(level2Data,quotaId,6,3);
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,7,3,-1);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("----------7-----------");
    }
    private void computequota_8()throws Exception {
         errorContent=new StringBuffer();
    private void computequota_8(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies)throws Exception {
        String quotaId="8";
        //找出今天的签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(now, tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>> patientAgeRoleData= patientAgeRole.elt(returnData1s);
            //找出今天的签约信息
           // String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2  and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
           // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Age,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);;
            //保存数据
            redisStorage.saveByLevel2(patientAgeRoleData,quotaId,6,2);
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,6,2);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("----------8-----------");
    }
    private void computequota_9() {
         errorContent=new StringBuffer();
        String quotaId="9";
        //找出今天的待签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingWaitSignYesterdayExpensesStatus(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||(idCard.length()!=18&&idCard.length()!=15)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where   a.type =2  and a.status=0 and  a.patient_apply_date< '"+tomorrow+"'  ";
        try{
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("----------9-----------");
         allContent.append("----------9-----------");
    }
    private void computequota_10() {
         errorContent=new StringBuffer();
        String quotaId="10";
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的已改簽信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingChaangeSignYesterdayExpensesStatus(now,tomorrow);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||(idCard.length()!=18&&idCard.length()!=15)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
       try{
            //找出今天的已改簽信息
            String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and a.status =100 and   a.patient_apply_date< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            redisStorage.saveByLevel1(returnDatas,quotaId);
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append(saveContent(quotaId,signFamilys.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        allContent.append("-----------10----------");
    }
@ -1616,14 +545,6 @@ public class CurrentDayAllQuotaJob implements Job {
        return dateString;
    }
    public List<Map<String,Object>> getFvYesterday() {
        String now = getDayString(0);
        String tomorrow = getDayString(1);
        String sql=" select * from fv_plan a where unix_timestamp(a.update_time)>=unix_timestamp('"+now+"') and unix_timestamp(a.update_time)< unix_timestamp('"+tomorrow+"')  ";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 根据年龄得到对应的code
     * @param age
@ -1644,16 +565,9 @@ public class CurrentDayAllQuotaJob implements Job {
            return Constant.level_age_6;
        }
    }
    private String getOrg(String org){
        //if(!"00".equals(org.substring(org.length()-2,org.length()))){
        if(org.length() == 10 && !org.endsWith("00")){
            return org.substring(0,org.length()-2)+"00";
        }else{
            return org;
        }
    }
    private String saveContent(String id,Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计 quotaid:"+id+" 的数据完成 ,数据库查询到改签数目:"+size);
        StringBuffer string=new StringBuffer("统计 quotaid:"+id+" 的数据完成 ,数据库查询到签约数目:"+size);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);

+ 53 - 164
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/FollowUpJob.java

@ -1,7 +1,9 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.FollowUpDataFilter;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
@ -10,12 +12,11 @@ import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
@ -34,6 +35,7 @@ import java.util.*;
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class FollowUpJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
@ -42,27 +44,21 @@ public class FollowUpJob implements Job {
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private JdbcTemplate jdbcTemplate_wlyy;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    private org.apache.tomcat.jdbc.pool.DataSource fvdataSource=new org.apache.tomcat.jdbc.pool.DataSource();//随访数据源
    @Autowired
    private FollowUpDataFilter followUpDataFilter;
    private org.apache.tomcat.jdbc.pool.DataSource fvdataSource = new org.apache.tomcat.jdbc.pool.DataSource();//随访数据源
    private JdbcTemplate jdbcTemplate = new JdbcTemplate();
    String yesterday;
    String now;
    String daybefore;
    @Value("${fv.jdbc.driver}")
    String fv_jdbc_driver;
    @Value("${fv.jdbc.url}")
@ -75,7 +71,7 @@ public class FollowUpJob implements Job {
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try{
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            JobDataMap map = context.getJobDetail().getJobDataMap();
@ -89,161 +85,58 @@ public class FollowUpJob implements Job {
            //计算指标
            jdbcTemplate.setDataSource(fvdataSource);//初始化随访的数据源
            //線刪除今天的数据
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            daybefore = StringUtils.isEmpty(map.get("daybefore")) ? SignJob.getDayString(-2) : map.get("daybefore").toString();
            yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignJob.getDayString(-1) : map.get("yesterday").toString();
            computequota();
        }catch (Exception e){
        } catch (Exception e) {
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }
    @Transactional
    private void computequota() {
        jdbcTemplate_wlyy.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+4+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的随访信息
        List<Map<String,Object>> plans = getFvYesterday();
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(Map<String,Object> plan:plans){
            ETLModel etlModel=new ETLModel();
            Object idCard=plan.get("id_card");//得到隨訪的身份證
            if(StringUtils.isEmpty(idCard)){
                errorContent.append("随访id:"+plan.get("id")+",随访(fv_plan)表id_card为空");
                isAll=false;
                continue;
            }
            SignFamily signFamily=signFamilyDao.findByIdcard(idCard.toString());
            if(signFamily==null){
                errorContent.append("随访id:"+plan.get("id")+",签约code:,随访中的患者身份证在签约表中找不到数据");
                isAll=false;
                continue;
            }
            Long adminTeamId=signFamily.getAdminTeamId();
            if(adminTeamId==null||adminTeamId<=0){
                errorContent.append("随访id:"+plan.get("id")+",签约code:"+signFamily.getCode()+" 中的adminTeamId为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId());
            if(adminTeam==null){
                errorContent.append("随访id:"+plan.get("id")+",签约code:"+signFamily.getCode()+",医生团队不存在");
                isAll=false;
                continue;
            }
            //统计机构------------------start ------------------
            //判断医生属于哪个机构
            String orgCodeTemp="";
            String orgCode=adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("随访id:"+plan.get("id")+",团队Id:"+adminTeam.getId()+",随访的医生所属的团队(wlyy_admin_team)机构为空");
                isAll=false;
                continue;
            }
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital==null){
                errorContent.append("随访id:"+plan.get("id")+",团队Id:"+adminTeam.getId()+",随访的医生所属的团队的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("随访id:"+plan.get("id")+",机构Id:"+hospital.getId()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("随访id:"+plan.get("id")+",机构Id:"+hospital.getId()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
        try {
            jdbcTemplate_wlyy.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 4 + "'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            String sql = " select * from fv_plan a where a.update_time>='" + daybefore + Constant.quota_date_last + "' and a.update_time< '" + yesterday + Constant.quota_date_last + "'  ";
            //找出今天的随访信息
            List<Map<String, Object>> plans = jdbcTemplate.queryForList(sql);
            FilterModel etlModels = followUpDataFilter.filter(plans, sql, yesterday);
            // 统计数据
            List<Map<String, List<ETLModel>>> returnDatas = levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
        }catch (Exception e){
            dbStorage.saveByLevel1(returnDatas, yesterday, wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError() ? "1" : "0");
            quartzJobLogDao.save(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(plans,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<Map<String, Object>> plans, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的随访完成 ,数据库查询到随访数目:"+plans.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
    private String saveContent(List<Map<String, Object>> plans, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount, String sql) {
        StringBuffer string = new StringBuffer("统计" + yesterday + " 的随访完成 ,数据库查询到随访数目:" + plans.size());
        string.append(",sql语句:" + sql);
        string.append(",过滤的脏数据数目:" + errorCount);
        string.append(",统计到市的数据总数:" + cityCount);
        string.append(",统计到区的数据总数:" + townCount);
        string.append(",统计到机构的数据总数:" + orgCount);
        string.append(",统计到团队的数据总数:" + qkCount);
        string.append(",是否统计成功:" + isAll);
        if (!isAll) {
            string.append(",失败原因:" + errorContent);
        }
        return string.toString();
    }
@ -252,10 +145,6 @@ public class FollowUpJob implements Job {
        return yesterday;
    }
    public List<Map<String,Object>> getFvYesterday() {
        String sql=" select * from fv_plan a where unix_timestamp(a.update_time)>=unix_timestamp('"+yesterday+"') and unix_timestamp(a.update_time)< unix_timestamp('"+now+"')  ";
        return jdbcTemplate.queryForList(sql);
    }
    private void save(Map<String, Long> tjTownMap, String city, String cityName, String town, String townName, String org, String orgName, String doctorCode, String doctorName, String doctorJob, String level, String key) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setDel("1");
@ -282,10 +171,10 @@ public class FollowUpJob implements Job {
        wlyyQuotaResultDao.save(wlyyQuotaResult);
    }
    private String getOrg(String org){
        if(!"00".equals(org.substring(org.length()-2,org.length()))){
            return org.substring(0,org.length()-2)+"00";
        }else{
    private String getOrg(String org) {
        if (!"00".equals(org.substring(org.length() - 2, org.length()))) {
            return org.substring(0, org.length() - 2) + "00";
        } else {
            return org;
        }
    }

+ 38 - 133
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/HealthGuideJob.java

@ -1,23 +1,27 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.HealthGuideDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
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 org.springframework.transaction.annotation.Transactional;
@ -31,31 +35,25 @@ import java.util.*;
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class HealthGuideJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private PatientHealthGuidanceDao patientHealthGuidanceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private HealthGuideDataFilter healthGuideDataFilter;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
@ -66,7 +64,7 @@ public class HealthGuideJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
@ -79,131 +77,38 @@ public class HealthGuideJob implements Job {
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+3+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+5+"'");
        //找出全部的团队
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的健康指导信息
        List<PatientHealthGuidance> patientHealthGuidances = patientHealthGuidanceDao.findByCzrqyYesterday(yesterday,now);
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(PatientHealthGuidance patientHealthGuidance:patientHealthGuidances){
            ETLModel etlModel=new ETLModel();
            String patient=patientHealthGuidance.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",患者code:"+patient+",家庭签约不存在");
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamId()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的团队AdminTeamCode为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的团队不存在");
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",签约code:"+signFamily.getCode()+",咨询的家庭签约的机构Hospital不存在");
                isAll=false;
                continue;
            }
            String orgCodeTemp="";
            //统计机构 -----------------start---------------------
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+orgCodeTemp+",健康咨询的医生所属的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+hospital.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("健康咨询id:"+patientHealthGuidance.getId()+",机构code:"+hospital.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //找出今天的健康指导信息
            String sql="SELECT patient,id FROM wlyy_patient_health_guidance a WHERE a.czrq>='"+daybefore+ Constant.quota_date_last+"' and a.czrq< '"+yesterday+ Constant.quota_date_last+"'";
            //抽取數據
            List<PatientHealthGuidance> consultTeams= dbExtract.extract(PatientHealthGuidance.class,sql);
            //過濾數據
            FilterModel etlModels= healthGuideDataFilter.filter(consultTeams,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(patientHealthGuidances,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<PatientHealthGuidance> patientHealthGuidances, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount) {
    private String saveContent(List<PatientHealthGuidance> patientHealthGuidances, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount,String sql) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的健康指导数据完成 ,数据库查询到健康指导数目:"+patientHealthGuidances.size());
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);

+ 36 - 163
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/HealthSignJob.java

@ -1,22 +1,21 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.Level2Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
@ -27,6 +26,7 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * Created by Administrator on 2016.10.13.
@ -34,18 +34,13 @@ import java.util.*;
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class HealthSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
@ -54,12 +49,12 @@ public class HealthSignJob implements Job {
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    private SignDataFilter signDataFilter;
    @Autowired
    private SignPatientLabelInfoDao signPatientLabelInfoDao;
    private CachePool cachePool;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
@ -69,7 +64,7 @@ public class HealthSignJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
@ -85,155 +80,33 @@ public class HealthSignJob implements Job {
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+15+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            //查找每个患者的健康分布标签
            List<SignPatientLabelInfo> signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"2",1);
            String level2Key="0";
            if(signPatientLabelInfoList!=null&&signPatientLabelInfoList.size()>0){
                level2Key=signPatientLabelInfoList.get(0).getLabel();
            }
            etlModel.setLevel2Key(level2Key);//设置二级维度的Key
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+15+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(), SignDataFilter.level2Health,cacheModel.getSql(),yesterday);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= level2Role.elt(returnDatas);
            //保存数据
            dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,4,5,0);
            dbStorage.saveByLevel2(patientSexRoleData,yesterday,wlyyQuota,4,5,0);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的签约数据完成 ,数据库查询到签约数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    public String getYesterday() {

+ 1 - 2
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/QuartzHelper.java

@ -101,9 +101,8 @@ public class QuartzHelper {
        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger-id:" + id, "group-group:" + id)
                .startAt(time)
                .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(0))
                .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(0).withMisfireHandlingInstructionFireNow())
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }

+ 46 - 334
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignAgeGroupDiseaseJob.java

@ -1,24 +1,22 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.*;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -27,34 +25,36 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 签约下按年龄分组后再按疾病统计
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class SignAgeGroupDiseaseJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    private Level1Role levelRole;
    @Autowired
    private HospitalDao hospitalDao;
    private Level2Role level2Role;
    @Autowired
    private TownDao townDao;
    private Level3Role level3Role;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private DBStorage dbStorage;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
@ -65,7 +65,7 @@ public class SignAgeGroupDiseaseJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now = StringUtils.isEmpty(map.get("now")) ? SignAgeGroupDiseaseJob.getDayString(0) : map.get("now").toString();
            daybefore = StringUtils.isEmpty(map.get("daybefore")) ? SignAgeGroupDiseaseJob.getDayString(-2) : map.get("daybefore").toString();
            yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignAgeGroupDiseaseJob.getDayString(-1) : map.get("yesterday").toString();
            computequotaByPatientAge();
@ -80,316 +80,35 @@ public class SignAgeGroupDiseaseJob implements Job {
     */
    @Transactional
    private void computequotaByPatientAge() {
        try {
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+12+"'");
            //新建任务日志对象
            QuartzJobLog wlyyJobLog = new QuartzJobLog();
            wlyyJobLog.setJobStartTime(new Date());
            wlyyJobLog.setJobId(wlyyJobConfig.getId());
            wlyyJobLog.setJobName(wlyyJobConfig.getJobName());
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospital2();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            //找出今天的签约信息
            List<SignFamily> signFamilies = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
            //数组里面第一个是健康人群 第二个是慢病人群 第三个是65岁以上人群
            Map<String, Map<String, Map>> cityAgeMap = new HashMap<String, Map<String, Map>>();//key是市行政代码 目前只有厦门市
            Map<String,Map> temp =new HashMap<String,Map>();
            cityAgeMap.put(Constant.city, temp);
            Map<String, Map<String, Map>> townAgeMap = new HashMap<String, Map<String, Map>>();//key是区行政代码
            Map<String, Map<String, Map>> orgAgeMap = new HashMap<String, Map<String, Map>>();//key是机构代码
            //统计有签约的
            Long cityCount = 0L; //统计到市的数目
            Long townCount = 0L; //统计到所有区的数目
            Long orgCount = 0L;//统计到所有机构的数目
            Long qkCount = 0L;//统计到所有全科医生的数目
            Long errorCount=0L;
            boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            for (SignFamily signFamily : signFamilies) {
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                int age = IdCardUtil.getAgeForIdcard(idCard);//根据card解析年龄
                String ageCode = getAgeCode(age);//得到年龄的code
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
                boolean hasGXY = false;//有高血压
                boolean hasTNB = false;//有糖尿病
                //如果是慢病的 统计高血压的 糖尿病  1高血压,2糖尿病  3 糖尿病和高血压 4健康人群数
                String diseaseType="";
                String jsonString = redisTemplate.opsForValue().get("disease:" + signFamily.getPatient());
                if (StringUtils.isEmpty(jsonString)) {
                    diseaseType="4";//健康人群
                }else{
                    //排除数据 只留下高血压和糖尿病
                    List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
                    JSONArray redisValues = new JSONArray(jsonString);
                    if(redisValues.length()>0){
                        for (Object obj : redisValues) {
                            JSONObject redisValue = (JSONObject)(obj);
                            if(!redisValue.has("signType")){
                                continue;
                            }
                            //排除掉三师签约
                            if ("1".equals(redisValue.get("signType").toString())) {
                                continue;
                            }
                            String disease =  redisValue.getString("disease");
                            if ("1".equals(disease)) {
                                jsonObjects.add(redisValue);
                                hasGXY = true;//设置有高血压
                                diseaseType="1";
                            }
                            if ("2".equals(disease)) {
                                jsonObjects.add(redisValue);
                                hasTNB = true;//设置有糖尿病
                                diseaseType="2";
                            }
                        }
                        if(hasGXY&&hasTNB){
                            diseaseType="3";//高血压和糖尿病
                        }
                    }else{
                        diseaseType="4";//健康人群
                    }
                }
                //统计市
                compute(cityAgeMap, Constant.city, ageCode, diseaseType);
                cityCount++;
                //统计区
                compute(townAgeMap, town, ageCode, diseaseType);
                townCount++;
                //统计机构
                //统计站
                orgCode=hospital.getCode();
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //统计站
                     orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                    //统计机构
                    compute(orgAgeMap, orgCodeTemp, ageCode, diseaseType);
                } else {
                    compute(orgAgeMap, hospital.getCode(), ageCode, diseaseType);
                }
                orgCount++;
            }
            //保存统计数据
            // 保存市的统计数据
            for (Map.Entry<String, Map<String, Map>> entry : cityAgeMap.entrySet()) {
               Map<String, Map> oneAgeMap = entry.getValue();
               for(int i=1;i<7;i++){
                   for(int j=1;j<5;j++){
                       String key_2=i+"";
                       String key_3=j+"";
                       String city=Constant.city;
                       String cityName=Constant.cityName;
                       String town="";
                       String townName="";
                       String org="";
                       String orgName="";
                       save(oneAgeMap, key_2, key_3, city, cityName, town, townName, org, orgName,"4");
                   }
               }
            }
            //保存区级
            for (Map.Entry<String, Town> entry : townsMap.entrySet()) {
                //判断该区是否有统计数据
                Map<String, Map> oneAgeMap = townAgeMap.get(entry.getKey());//得到当个区的统计数据
                Town townObj = entry.getValue();//得到区级信息
                for(int i=1;i<7;i++){
                    for(int j=1;j<5;j++){
                        String key_2=i+"";
                        String key_3=j+"";
                        String city=Constant.city;
                        String cityName=Constant.cityName;
                        String town=townObj.getCode();
                        String townName=townObj.getName();
                        String org="";
                        String orgName="";
                        save(oneAgeMap, key_2, key_3, city, cityName, town, townName, org, orgName,"3");
                    }
                }
            }
            for (Map.Entry<String, Hospital> entry : hospitalsMap.entrySet()) {
                //判断该机构是否有统计数据
                Map<String, Map> oneAgeMap = orgAgeMap.get(entry.getKey());//得到当个机构的统计数据
                Hospital hospital = entry.getValue();//得到机构信息
                for(int i=1;i<7;i++){
                    for(int j=1;j<5;j++){
                        Hospital hospital1=entry.getValue();
                        if(hospital1==null)continue;
                        String key_2=i+"";
                        String key_3=j+"";
                        String city=Constant.city;
                        String cityName=Constant.cityName;
                        String town=hospital.getTown();
                        String townName=hospital.getTownName();
                        String org=hospital.getCode();
                        String orgName=hospital.getName();
                        save(oneAgeMap, key_2, key_3, city, cityName, town, townName, org, orgName,"2");
                    }
                }
            }
            wlyyJobLog.setJobEndTime(new Date());
            wlyyJobLog.setJobContent(saveContent(signFamilies,qkCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            wlyyJobLog.setJobType(isAll?"1":"0");
            quartzJobLogDao.save(wlyyJobLog);
        } catch (Exception e) {
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2Age,SignDataFilter.level3Disease,cacheModel.getSql(),yesterday);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= level2Role.elt(returnDatas);
            //统计数据 三级维度
            List<Map<String, Map<String, Map<String, List<ETLModel>>>>> returnD=level3Role.elt(patientSexRoleData);
            //保存数据
            dbStorage.saveByLevel3(returnD,yesterday,wlyyQuota,6,4,2,1);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的签约数据完成 ,数据库查询到签约数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    private void save(Map<String, Map> oneAgeMap, String key_2, String key_3, String city, String cityName, String town, String townName, String org, String orgName,String level) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setDel("1");
        wlyyQuotaResult.setCity(city);
        wlyyQuotaResult.setCityName(cityName);
        wlyyQuotaResult.setTown(town);
        wlyyQuotaResult.setTownName(townName);
        wlyyQuotaResult.setOrgCode(org);
        wlyyQuotaResult.setOrgName(orgName);
        wlyyQuotaResult.setQuatoCode(wlyyQuota.getId());
        wlyyQuotaResult.setQuatoName(wlyyQuota.getName());
        wlyyQuotaResult.setQuotaDate(getYesterday());
        wlyyQuotaResult.setCreateTime(new Date());
        wlyyQuotaResult.setLevel1Type(level);//等级
        wlyyQuotaResult.setLevel2Type(key_2);
        wlyyQuotaResult.setLevel2TypeName(Constant.getLevelAgeName(key_2));
        wlyyQuotaResult.setLevel3Type(key_3);
        wlyyQuotaResult.setLevel3TypeName(Constant.getLevelDiseaseName(key_3));
        if (oneAgeMap != null && oneAgeMap.containsKey(key_2)) {
            Map<String,Long> key3Map=oneAgeMap.get(key_2);
            if(key3Map!=null&&key3Map.containsKey(key_3)){
                wlyyQuotaResult.setResult(key3Map.get(key_3) + "");
            }else{
                wlyyQuotaResult.setResult("0");
            }
        } else {
            wlyyQuotaResult.setResult("0");
        }
        wlyyQuotaResultDao.save(wlyyQuotaResult);
    }
    /**
     * 统计方案
     * @param rootMap 数据存放的map
     * @param rootKey 数据的key 机构 区  市
     * @param ageCode 年龄的key
     * @param diseaseType 疾病类型 1是高血压 2是糖尿病 3是高血压和糖尿病 4是健康人群
     */
    private void compute(Map<String, Map<String, Map>> rootMap, String rootKey, String ageCode, String diseaseType) {
        if (rootMap.containsKey(rootKey)) {
            //得到市下面的所有的年龄map
            Map<String, Map> groupMapTemp = rootMap.get(rootKey);
            if(groupMapTemp.containsKey(ageCode)){
                //得到这个年龄下的患者map
                Map<String,Long> mape= groupMapTemp.get(ageCode);
                if(mape.containsKey(diseaseType)){
                    mape.put(diseaseType,mape.get(diseaseType)+1L); //key是三级维度
                }else{
                    mape.put(diseaseType,1L); //key是三级维度
                }
            }else{
                //新增疾病的统计map
                Map<String, Long> groupMapTemp1 = new HashMap<String, Long>();
                groupMapTemp1.put(diseaseType, 1L);//key是三级维度
                groupMapTemp.put(ageCode,groupMapTemp1);//key是二级维度
            }
        } else {
            //没有就新建统计数据  新增疾病的统计map
            Map<String, Long> groupMapTemp = new HashMap<String, Long>();
            groupMapTemp.put(diseaseType, 1L); //key是三级维度
            //把统计疾病的map放入对应的年龄组map中
            Map<String, Map> groupMapTemp2 = new HashMap<String, Map>();
            groupMapTemp2.put(ageCode,groupMapTemp); //key是二级维度
            //把年龄组map放入市的map里面
            rootMap.put(rootKey, groupMapTemp2); //key是一级维度
        }
    }
    /*
    得到昨天的日期字符串  yyyy-MM-dd
     */
@ -403,7 +122,7 @@ public class SignAgeGroupDiseaseJob implements Job {
     * @param age
     * @return
     */
    public String getAgeCode(int age) {
    public String getAgeCode(Integer age) {
        if (age < 7) {
            return Constant.level_age_1;
        } else if (age >= 7 && age < 18) {
@ -429,13 +148,6 @@ public class SignAgeGroupDiseaseJob implements Job {
        String dateString = formatter.format(date);
        return dateString;
    }
    private String getOrg(String org){
        if(!"00".equals(org.substring(org.length()-2,org.length()))){
            return org.substring(0,org.length()-2)+"00";
        }else{
            return org;
        }
    }
    public static void main(String[] args) {
        getDayString(0);
    }

+ 130 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignExpenseStatusJob.java

@ -0,0 +1,130 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.Level2Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
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.*;
import java.util.Calendar;
/**
 * Created by Administrator on 2016.10.11.
 * 签约费用统计 到达量
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class SignExpenseStatusJob implements Job{
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String date; //起始时间
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            date = StringUtils.isEmpty(map.get("yesterday")) ? SignJob.getDayString(-1) : map.get("yesterday").toString();
            //计算指标
            computequota();
        }catch (Exception e){
            e.printStackTrace();
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }
    /**
     * 计算指标
     */
    private void computequota()throws Exception {
        try {
            deleteData();
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(date);
            List<SignFamily> signFamilies_1=cacheModel.getSignFamilies();
            //抽取第二种条件的语句
            String sql=" select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"' and (expenses_status !=1 or expenses_status is null)";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            List<SignFamily> signFamilies_2= dbExtract.extractByPage(SignFamily.class,sql,sqlCount,true);
            signFamilies_2.addAll(signFamilies_1);
            //抽取的语句
            sql="select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'";
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies_2, SignDataFilter.level2Expenses,sql,date);
            //统计数据
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= level2Role.elt(returnDatas);
            //数据转换
            dbStorage.saveByLevel2(level2Data,date,wlyyQuota,2,4,0);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            dbStorage.saveLog(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Transactional
    private void deleteData() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + date + "' and quato_code='" + 16 + "'");
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
}

+ 84 - 556
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/SignJob.java

@ -1,31 +1,23 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.Level2Role;
import com.yihu.wlyy.statistics.etl.role.PatientAgeRole;
import com.yihu.wlyy.statistics.etl.role.PatientSexRole;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -34,48 +26,34 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 签约的指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class SignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private PatientAgeRole patientAgeRole;
    @Autowired
    private PatientSexRole patientSexRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private SignPatientLabelInfoDao signPatientLabelInfoDao;
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
@ -86,7 +64,7 @@ public class SignJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now = StringUtils.isEmpty(map.get("now")) ? SignJob.getDayString(0) : map.get("now").toString();
            daybefore = StringUtils.isEmpty(map.get("daybefore")) ? SignJob.getDayString(-2) : map.get("daybefore").toString();
            yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignJob.getDayString(-1) : map.get("yesterday").toString();
            String level1 = wlyyQuota.getLevel1();//得到一级维度
            String level2 = wlyyQuota.getLevel2();//得到二级维度
@ -137,123 +115,20 @@ public class SignJob implements Job {
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //查找出系统全部的团队
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            //找出今天的签约信息
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
            Long cityCount = new Long(0L); //统计到市的数目
            Long townCount = new Long(0L); //统计到所有区的数目
            Long orgCount =new Long(0L);//统计到所有机构的数目
            Long adminCount = new Long(0L);//统计到所有团队的数目
            Long errorCount=new Long(0L);//脏数据
            Boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            //统计有已改簽的
            List<ETLModel> etlModels=new ArrayList<ETLModel>();
            //数据过滤清洗出脏数据  -----------start
            for(SignFamily signFamily:signFamilys){
                ETLModel etlModel=new ETLModel();
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
                //统计数目+1
                cityCount++;
                townCount++;
                orgCount++;
                adminCount++;
            }
            //数据过滤清洗出脏数据  -----------end
            try{
                //统计数据
                List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
                List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= patientSexRole.elt(returnData1s);
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2Sex,cacheModel.getSql(),yesterday);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);;
                //保存数据
                dbStorage.saveByLevel2(patientSexRoleData,yesterday,wlyyQuota,3,1);
            }catch (Exception e){
                e.printStackTrace();
                errorContent.append("统计失败:"+e.getMessage());
            }
            dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,3,1);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            quartzJobLog.setJobType(isAll?"1":"0");
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
@ -264,170 +139,38 @@ public class SignJob implements Job {
     */
    @Transactional
    private void computequotaByPatientGroup() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+15+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的解约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingUnSignYesterdayExpensesStatus(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            //得到患者的分组标签
            List<SignPatientLabelInfo> signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"1",1);
            String level2Key="1";
            if(signPatientLabelInfoList!=null&&signPatientLabelInfoList.size()>0){
                level2Key=signPatientLabelInfoList.get(0).getLabel();
            }
            etlModel.setLevel2Key(level2Key);//设置二级维度的Key
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            if("2".equals(level2Key)){
                level2Key="0";
                boolean hasGXY=false;//有高血压
                boolean hasTNB=false;//糖尿病
                //得到患者的疾病标签
                signPatientLabelInfoList= signPatientLabelInfoDao.findByPatientAndLabelTypeAndStatus(signFamily.getPatient(),"3",1);
                for (SignPatientLabelInfo signPatientLabelInfo:signPatientLabelInfoList){
                    if("1".equals(signPatientLabelInfo.getLabel())){
                        level2Key="4";
                        hasGXY=true;
                    }
                    if("2".equals(signPatientLabelInfo.getLabel())){
                        level2Key="5";
                        hasTNB=true;
                    }
                }
                if (hasTNB&&hasGXY){
                    level2Key="6";
                }
                etlModel=new ETLModel();
                etlModel.setLevel2Key(level2Key);//设置二级维度的Key
                etlModel.setAdminTeam(adminTeam.getId()+"");
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
            }
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+7+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的解约信息
            //String sql=" select code,idcard,hospital,admin_team_code,patient from wlyy_sign_family a where  a.type =2 and   a.expenses_time< '"+yesterday+ Constant.quota_date_last+"' and a.expenses_status=1 ";
            //抽取數據
            //List<SignFamily> signFamilies= dbExtract.extract(SignFamily.class,sql);
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2Group,cacheModel.getSql(),yesterday);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);
            //保存数据 1 表示:从1开始循环 6表示:循环6次 3表示 2级维度是 3
            dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,6,3,1);
             dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,7,3,-1);
            //dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,6,3,-1);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
@ -443,122 +186,20 @@ public class SignJob implements Job {
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //查找出系统全部的团队
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospital2();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            //找出今天的签约信息
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
            Long cityCount = new Long(0L); //统计到市的数目
            Long townCount = new Long(0L); //统计到所有区的数目
            Long orgCount =new Long(0L);//统计到所有机构的数目
            Long adminCount = new Long(0L);//统计到所有团队的数目
            Long errorCount=new Long(0L);//脏数据
            Boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            //统计有已改簽的
            List<ETLModel> etlModels=new ArrayList<ETLModel>();
            //数据过滤清洗出脏数据  -----------start
            for(SignFamily signFamily:signFamilys){
                ETLModel etlModel=new ETLModel();
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
                //统计数目+1
                cityCount++;
                townCount++;
                orgCount++;
                adminCount++;
            }
            //数据过滤清洗出脏数据  -----------end
            try{
                //统计数据
                List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
                List<Map<String, Map<String, List<ETLModel>>>> patientAgeRoleData= patientAgeRole.elt(returnData1s);
                //保存数据
                dbStorage.saveByLevel2(patientAgeRoleData,yesterday,wlyyQuota,6,2);
            }catch (Exception e){
                e.printStackTrace();
                errorContent.append("统计失败:"+e.getMessage());
            }
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2Age,cacheModel.getSql(),yesterday);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);;
            //保存数据
            dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,6,2);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            quartzJobLog.setJobType(isAll?"1":"0");
            quartzJobLog.setJobEndTime(new Date());;
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
@ -570,132 +211,33 @@ public class SignJob implements Job {
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 1 + "'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的团队
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的签约信息 yesterday,now
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 1 + "'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的签约信息 yesterday,now
           // String sql=" select code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.expenses_time< '"+yesterday+ Constant.quota_date_last+"' and a.expenses_status=1 ";
            //抽取數據
           // List<SignFamily> signFamilies= dbExtract.extract(SignFamily.class,sql);
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),cacheModel.getSql(),yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    /*
    得到昨天的日期字符串  yyyy-MM-dd
@ -715,18 +257,4 @@ public class SignJob implements Job {
        return dateString;
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的签约数据完成 ,数据库查询到签约数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}

+ 34 - 146
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/UnSignJob.java

@ -1,7 +1,10 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
@ -9,14 +12,14 @@ import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
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 org.springframework.transaction.annotation.Transactional;
@ -25,34 +28,32 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 解约的指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class UnSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    String yesterday;
    String now;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
@ -62,7 +63,7 @@ public class UnSignJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
@ -78,148 +79,35 @@ public class UnSignJob implements Job {
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+2+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的解约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingUnSignYesterdayExpensesStatus(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+2+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的解约信息
            String sql=" select code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and a.status in(-3,-4) and a.apply_unsign_date< '"+yesterday+ Constant.quota_date_last+"'";
            //抽取數據
            List<SignFamily> signFamilies= dbExtract.extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的解约数据完成 ,数据库查询到解约数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();

+ 34 - 146
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/WaitSignJob.java

@ -1,7 +1,10 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
@ -9,14 +12,14 @@ import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.json.JSONObject;
import org.quartz.*;
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 org.springframework.transaction.annotation.Transactional;
@ -25,34 +28,32 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
/**
 * 待签约的指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class WaitSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    String yesterday;
    String now;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
@ -62,7 +63,7 @@ public class WaitSignJob implements Job {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            now= StringUtils.isEmpty(map.get("now"))?SignJob.getDayString(0):map.get("now").toString();
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
@ -78,147 +79,34 @@ public class WaitSignJob implements Job {
     */
    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+9+"'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的待签约信息
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingWaitSignYesterdayExpensesStatus(yesterday,now);
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code:"+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code:"+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+9+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的待签约信息
            String sql=" select code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2  and a.status=0 and  a.patient_apply_date< '"+yesterday+ Constant.quota_date_last+"'  ";
            //抽取數據
            List<SignFamily> signFamilies= dbExtract.extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的待签约数据完成 ,数据库查询到待签约数目:"+signFamilys.size());
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();

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

@ -80,25 +80,25 @@ public class CheckSignJob implements Job{
                params.put("quota", wlyyQuotaVO);
                params.put("jobConfig", wlyyJobConfigVO);
                String now=getNextDate(wlyyQuotaResult.getQuotaDate());
                String daybefore=getNextDate(wlyyQuotaResult.getQuotaDate());
                String yesterday=wlyyQuotaResult.getQuotaDate();
                //往quartz框架添加任务
                params.put("now", now);
                params.put("daybefore", daybefore);
                params.put("yesterday", yesterday);
                String jobKey="checkSignQuartz:"+wlyyQuotaResult.getQuotaDate()+":"+wlyyQuotaResult.getQuatoCode();
                if(!quartzHelper.isExistJob(jobKey)){
                    quartzHelper.startAt(weeHours(new Date(),1),SignJob.class,jobKey,params);
                    //重新生成性别 疾病 扣费 和 年龄的统计
                    startJob("6",yesterday,now);
                    startJob("7",yesterday,now);
                    startJob("8",yesterday,now);
                    startJob("12",yesterday,now);
                    startJob("6",yesterday,daybefore);
                    startJob("7",yesterday,daybefore);
                    startJob("8",yesterday,daybefore);
                    startJob("12",yesterday,daybefore);
                }
            }
        }
    }
    private void startJob(String id, String yesterday, String now) throws Exception{
    private void startJob(String id, String yesterday, String daybefore) throws Exception{
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
@ -114,7 +114,7 @@ public class CheckSignJob implements Job{
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        params.put("now", now);
        params.put("daybefore", daybefore);
        params.put("yesterday", yesterday);
        String jobKey="checkSignQuartz:"+yesterday+":"+wlyyQuota.getId();
        if(!quartzHelper.isExistJob(jobKey)){
@ -185,7 +185,7 @@ public class CheckSignJob implements Job{
        Date dateTime=  DateUtil.strToDateShort(date);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dateTime);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nextDateTime=calendar.getTime();
        return DateUtil.dateToStrShort(nextDateTime);
    }

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

@ -38,15 +38,15 @@ public class ConsultTeam extends IdEntity {
	private Integer patientRead;    // 患者未读数量
	private Date czrq;              // 咨询时间
	private String del;             // 作废标识,1正常,0作废
	private Long adminTeamId;//行政团队ID
	private Long adminTeamCode;//行政团队ID
	@Column(name = "admin_team_code")
	public Long getAdminTeamId() {
		return adminTeamId;
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamId(Long adminTeamId) {
		this.adminTeamId = adminTeamId;
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getConsult() {

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

@ -58,6 +58,7 @@ public class Doctor extends IdEntity {
	private String idcard;          //身份证号
	private Integer isFamous;       //是否是名医 1是  0或者空不是
	private String isPasswordPrompt;// 是否提示密码信息 1是 0或者空是否
	public Doctor() {}
@ -348,4 +349,14 @@ public class Doctor extends IdEntity {
    public boolean isHealthDoctor(){
        return level == 3;
    }
	@Column(name = "is_password_prompt")
	public String getIsPasswordPrompt() {
		return isPasswordPrompt;
	}
	public void setIsPasswordPrompt(String isPasswordPrompt) {
		this.isPasswordPrompt = isPasswordPrompt;
	}
}

+ 7 - 29
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/signfamily/SignFamily.java

@ -59,7 +59,7 @@ public class SignFamily extends IdEntity {
	private String agentDoctorCode;//代理簽約人code
	private String agentDoctorName;//代理簽約人銘
	private String agentDoctorLevel;//代理簽約人等级
	private Long adminTeamId;//行政团队ID
	private Long adminTeamCode;//行政团队ID
	private Date expensesTime;//缴费时间
	public String getCode() {
@ -418,43 +418,21 @@ public class SignFamily extends IdEntity {
	}
	@Column(name = "admin_team_code")
	public Long getAdminTeamId() {
		return adminTeamId;
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamId(Long adminTeamId) {
		this.adminTeamId = adminTeamId;
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	@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 + '\'' +
				", expensesStatus='" + expensesStatus + '\'' +
				", 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 + '\'' +
				", adminTeamCode=" + adminTeamCode +
				'}';
	}

+ 100 - 22
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/JobService.java

@ -4,7 +4,10 @@ import com.yihu.wlyy.statistics.dao.DoctorPatientGroupInfoDao;
import com.yihu.wlyy.statistics.dao.QuartzJobConfigDao;
import com.yihu.wlyy.statistics.dao.QuotaDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.QuartzHelper;
import com.yihu.wlyy.statistics.job.cache.CacheCleanJob;
import com.yihu.wlyy.statistics.job.check.CheckSignJob;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
@ -18,6 +21,7 @@ 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.*;
@ -40,6 +44,8 @@ public class JobService {
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private CachePool cachePool;
    @Transactional
    public void stopById(String id) throws Exception {
@ -147,10 +153,11 @@ public class JobService {
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                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(20000L);
                }
            }
        }
@ -172,9 +179,9 @@ public class JobService {
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
@ -188,10 +195,11 @@ public class JobService {
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            //往quartz框架添加任务
            params.put("now", now);
            params.put("daybefore", daybefore);
            params.put("yesterday", yesterday);
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-",""), params);
                Thread.sleep(20000L);
            }
        }
@ -204,20 +212,7 @@ public class JobService {
     * @throws ClassNotFoundException
     */
    private Class getRightClass(QuartzJobConfig quartzJobConfig) throws ClassNotFoundException {
        String packageString="com.yihu.wlyy.statistics.job.business.";
        Class classTemp;
        try{
            classTemp=Class.forName(quartzJobConfig.getJobClass());
        }catch (Exception e){
            try{
            String classString=quartzJobConfig.getJobClass().replace("wlyy","wlyy.statistics").replace("job","job.business");
            classTemp=Class.forName(classString);
            }catch (Exception e1){
                packageString=packageString+quartzJobConfig.getJobClass().substring(quartzJobConfig.getJobClass().lastIndexOf("."));
                classTemp=Class.forName(packageString);
            }
        }
        return classTemp;
        return Class.forName(quartzJobConfig.getJobClass());
    }
    public void productDataByOneDayWithId(String yesterday, String id) throws Exception {
@ -228,9 +223,9 @@ public class JobService {
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
@ -247,7 +242,7 @@ public class JobService {
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        params.put("now", now);
        params.put("daybefore", daybefore);
        params.put("yesterday", yesterday);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-",""), params);
@ -310,10 +305,11 @@ public class JobService {
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                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(20000L);
                }
            }
    }
@ -329,4 +325,86 @@ public class JobService {
            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 static void main(String[] args) {
        System.out.println(getYesterday(0,new Date()));
    }
    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 startCleanCacheJob() throws  Exception {
        if(!quartzHelper.isExistJob(CacheCleanJob.jobKey)){
            quartzHelper.addJob(CacheCleanJob.class,CacheCleanJob.cron,CacheCleanJob.jobKey,new HashMap<>());
        }
    }
    public void stopCleanCacheJob()throws  Exception  {
        if(quartzHelper.isExistJob(CacheCleanJob.jobKey)){
            quartzHelper.removeJob(CacheCleanJob.jobKey);
        }
    }
    public void cleanCache() {
        CachePool.cleanAllCache();
    }
    public String seeCache() {
        Map<String, CacheModel> cacheModesCache= CachePool.getArriveSignFamilyExpenseStatus1Map();
        Map<String, String> patientGroupCache=CachePool.getPatientGroup();
        Map<String, String> healthGroupCache=CachePool.getHealthGroup();
        Map<String, List<String>> diseaseGroupCache=CachePool.getDiseaseGroup();
        String returnMessage=" 签约缓存:缓存存在"+cacheModesCache.size()+"天的缓存,";
        for(Map.Entry<String, CacheModel> entry:cacheModesCache.entrySet()){
               returnMessage+=entry.getKey()+",";
        }
        returnMessage+="patientGroupCache"+(patientGroupCache.size()>0?"有缓存":"没有缓存");
        returnMessage+="healthGroupCache"+(healthGroupCache.size()>0?"有缓存":"没有缓存");
        returnMessage+="diseaseGroupCache"+(diseaseGroupCache.size()>0?"有缓存":"没有缓存");
        return returnMessage;
    }
}

+ 4 - 3
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/PatientDiseaseToLabel.java

@ -7,6 +7,7 @@ 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;
@ -30,9 +31,9 @@ public class PatientDiseaseToLabel implements Runnable {
    public PatientDiseaseToLabel(Long start) {
        this.start = start;
        this.diseaseDao = Application.ctx.getBean(PatientDiseaseDao.class);
        this.labelInfoDao = Application.ctx.getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = Application.ctx.getBean(JpaTransactionManager.class);
        this.diseaseDao = SpringUtil.getApplicationContext().getBean(PatientDiseaseDao.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
    }
    @Override

+ 50 - 16
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/PatientGroupToLabelRunnable.java

@ -3,8 +3,10 @@ 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;
@ -30,9 +32,9 @@ public class PatientGroupToLabelRunnable implements Runnable {
    public PatientGroupToLabelRunnable(Long start, Long end) {
        this.start = start;
        this.end = end;
        this.groupInfoDao = Application.ctx.getBean(DoctorPatientGroupInfoDao.class);
        this.labelInfoDao = Application.ctx.getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = Application.ctx.getBean(JpaTransactionManager.class);
        this.groupInfoDao = SpringUtil.getApplicationContext().getBean(DoctorPatientGroupInfoDao.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
    }
    @Override
@ -67,8 +69,7 @@ public class PatientGroupToLabelRunnable implements Runnable {
        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> manbingLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> sixFiveLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> healthMap = new HashMap<>();
        List<DoctorPatientGroupInfo> groupInfos = groups.getContent();
@ -93,26 +94,59 @@ public class PatientGroupToLabelRunnable implements Runnable {
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            groupInfo.setStatus(2);
            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;
                }
            }
            SignPatientLabelInfo exLabelInfo = labelInfoDao.findByPatientAndLabelAndLabelTypeAndStatus(
                    groupInfo.getPatient(),labelInfo.getLabel(),"1",1);
            if (healthLabel == null) {
                healthLabel = new SignPatientLabelInfo();
            if(exLabelInfo != null){
                continue;
                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("患病人群");
            }
            normalLabel.put(groupInfo.getPatient(), labelInfo);
            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 (manbingLabel.size() > 0) {
            labelInfoDao.save(manbingLabel.values());
        }
        if (sixFiveLabel.size() > 0) {
            labelInfoDao.save(sixFiveLabel.values());
        if (healthMap.size() > 0) {
            labelInfoDao.save(healthMap.values());
        }
        groupInfoDao.save(groups);

+ 6 - 5
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/SignTeamAndGroupRunnable.java

@ -8,6 +8,7 @@ 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;
@ -40,11 +41,11 @@ public class SignTeamAndGroupRunnable implements Runnable {
    public SignTeamAndGroupRunnable(Long start, Long end){
        this.start = start;
        this.end = end;
        this.signFamilyDao = Application.ctx.getBean(SignFamilyDao.class);
        this.teamDao = Application.ctx.getBean(DoctorTeamDao.class);
        this.teamMemberDao = Application.ctx.getBean(DoctorTeamMemberDao.class);
        this.transactionManager = Application.ctx.getBean(JpaTransactionManager.class);
        this.labelInfoDao = Application.ctx.getBean(SignPatientLabelInfoDao.class);
        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() {

+ 27 - 25
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/IdCardUtil.java

@ -20,31 +20,30 @@ public class IdCardUtil {
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard(String CardCode)
            throws Exception {
        String sex = Constant.level_sex_3;
        if (CardCode.length() == 18) {
            if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                // modifid by lyr 2016-09-29
                // sex =  Constant.level_sex_2;
                sex = Constant.level_sex_1;
                // modifid by lyr 2016-09-29
            } else {
                // modifid by lyr 2016-09-29
                // sex =  Constant.level_sex_1;
                sex = Constant.level_sex_2;
                // modifid by lyr 2016-09-29
            }
        } else if (CardCode.length() == 15) {
            String usex = CardCode.substring(14, 15);// 用户的性别
            if (Integer.parseInt(usex) % 2 == 0) {
                // sex =  Constant.level_sex_2;
                sex = Constant.level_sex_1;
            } else {
                // sex =  Constant.level_sex_1;
                sex = Constant.level_sex_2;
    public static String getSexForIdcard(String CardCode) throws Exception{
        String sex = Constant.level_sex_2;
            if (CardCode.length() == 18) {
                if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                    // modifid by lyr 2016-09-29
                    // sex =  Constant.level_sex_2;
                    sex = Constant.level_sex_1;
                    // modifid by lyr 2016-09-29
                } else {
                    // modifid by lyr 2016-09-29
                    // sex =  Constant.level_sex_1;
                    sex = Constant.level_sex_2;
                    // modifid by lyr 2016-09-29
                }
            } else if (CardCode.length() == 15) {
                String usex = CardCode.substring(14, 15);// 用户的性别
                if (Integer.parseInt(usex) % 2 == 0) {
                    // sex =  Constant.level_sex_2;
                    sex = Constant.level_sex_1;
                } else {
                    // sex =  Constant.level_sex_1;
                    sex = Constant.level_sex_2;
                }
            }
        }
        return sex;
    }
@ -96,6 +95,7 @@ public class IdCardUtil {
     */
    public static int getAgeForIdcard(String idcard) {
        int age = 0;
        try{
        if (StringUtils.isEmpty(idcard)) {
            return age;
@ -118,7 +118,9 @@ public class IdCardUtil {
        if (cal.get(Calendar.MONTH) > (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) > day)) {
            age--;
        }
        }catch (Exception e){
            return age;
        }
        return age;
    }

+ 45 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/JsonDateValueProcessor.java

@ -0,0 +1,45 @@
package com.yihu.wlyy.statistics.util;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
 * Created by Administrator on 2016.10.20.
 */
public class JsonDateValueProcessor implements JsonValueProcessor {
    private String format ="yyyy-MM-dd HH:mm:ss";
    public JsonDateValueProcessor() {
        super();
    }
    public JsonDateValueProcessor(String format) {
        super();
        this.format = format;
    }
    @Override
    public Object processArrayValue(Object paramObject,
                                    JsonConfig paramJsonConfig) {
        return process(paramObject);
    }
    @Override
    public Object processObjectValue(String paramString, Object paramObject,
                                     JsonConfig paramJsonConfig) {
        return process(paramObject);
    }
    private Object process(Object value){
        if(value instanceof Date){
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(value);
        }
        return value == null ? "" : value.toString();
    }
}

+ 16 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/JsonUtil.java

@ -0,0 +1,16 @@
package com.yihu.wlyy.statistics.util;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import org.json.JSONObject;
import java.util.Date;
/**
 * Created by Administrator on 2016.10.20.
 */
public class JsonUtil {
    public static String objToStr(LogModel logModel){
        JSONObject jsonObject=new JSONObject(logModel);
        return jsonObject.toString();
    }
}

+ 64 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/MD5.java

@ -0,0 +1,64 @@
package com.yihu.wlyy.statistics.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
 * MD5 算法
 */
public class MD5 {
	// 全局数组
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	public MD5() {
	}
	// 返回形式为数字跟字符串
	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		// System.out.println("iRet="+iRet);
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}
	// 返回形式只为数字
//	private static String byteToNum(byte bByte) {
//		int iRet = bByte;
//		System.out.println("iRet1=" + iRet);
//		if (iRet < 0) {
//			iRet += 256;
//		}
//		return String.valueOf(iRet);
//	}
	// 转换字节数组为16进制字串
	private static String byteToString(byte[] bByte) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}
	public static String GetMD5Code(String strObj) {
		String resultString = null;
		try {
			resultString = new String(strObj);
			MessageDigest md = MessageDigest.getInstance("MD5");
			// md.digest() 该函数返回值为存放哈希值结果的byte数组
			resultString = byteToString(md.digest(strObj.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}
	public static void main(String[] args) {
		System.out.println(GetMD5Code("123456abcdefg"));
	}
}

+ 63 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/SpringUtil.java

@ -0,0 +1,63 @@
package com.yihu.wlyy.statistics.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }
    //获取applicationContext
    public static ApplicationContext
    getApplicationContext() {
        return applicationContext;
    }
    //通过name获取 Bean.
    public static Object
    getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    //通过class获取Bean.
    public static<T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    //通过name,以及Clazz返回指定的Bean
    public static<T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

+ 107 - 31
patient-co-statistics/src/main/resources/application.yml

@ -1,21 +1,43 @@
server:
  port: 8080
logging:
  level:
    com:
      netflix: ERROR
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50
    max-idle: 50
    min-idle: 10
    validation-query: SELECT 1
    test-on-borrow: true
    idle-timeout: 30000
  # REDIS
    primaryReadWrite:
      driver-class-name: com.mysql.jdbc.Driver
      max-active: 50
      max-idle: 50 #最大空闲连接
      min-idle: 10 #最小空闲连接
      validation-query-timeout: 20
      log-validation-errors: true
      validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
      validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
      test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
      test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
      idle-timeout: 30000
      connection-test-query: SELECT 1
      num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
      test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
      min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
      time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
    primaryRead:
      driver-class-name: com.mysql.jdbc.Driver
      max-active: 50
      max-idle: 50 #最大空闲连接
      min-idle: 10 #最小空闲连接
      validation-query-timeout: 20
      log-validation-errors: true
      validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
      validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
      test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
      test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
      idle-timeout: 30000
      connection-test-query: SELECT 1
      num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
      test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
      min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
      time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
    # REDIS
  redis:
    database: 0 # Database index used by the connection factory.
    port: 6379 # Redis server port.
@ -31,62 +53,116 @@ spring:
      max-wait: -1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
      min-idle: 1 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
multipart:
  max-file-size: 100MB
  max-request-size: 100MB
security:
  basic:
    username: jkzl
    password: jkzlehr@402803a657d14f9f0157d1517f183d50
logging:
  level:
    root: INFO
---
spring:
  profiles: dev
  profiles: cwd
  datasource:
    url: jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: root
    password: 123456
    primaryReadWrite:
      url: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: luofaqiang
      password: luofaqiang
    primaryRead:
      url: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: luofaqiang
      password: luofaqiang
  redis:
    host: 172.19.103.47 # Redis server host.
    host: 172.19.103.88
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.19.103.77/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: root
    password: 123456
    url: jdbc:mysql://172.19.103.85/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: luofaqiang
    password: luofaqiang
---
spring:
  profiles: test
  datasource:
    url: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg
    primaryReadWrite:
      url: jdbc:mysql://172.17.110.160/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: ssgg
      password: ssgg
    primaryRead:
      url: jdbc:mysql://172.17.110.160/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: ssgg
      password: ssgg
  redis:
      host: 172.19.103.88 # Redis server host.
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.19.103.85/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    url: jdbc:mysql://172.17.110.160/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg
---
spring:
  profiles: prod
  datasource:
    url: jdbc:mysql://11.1.2.24:3306/wlyy?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: wlyy
    password: jkzlehr@123
    primaryReadWrite:
      url: jdbc:mysql://59.61.92.94:3306/wlyy?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: wlyy
      password: jkzlehr@123
    primaryRead:
      url: jdbc:mysql://59.61.92.94:8883/wlyy?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: wlyy
      password: jkzlehr@123
  redis:
    host: 11.1.2.20 # Redis server host.
    password: java2000_wl
    host: 120.41.253.95 # Redis server host.
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://11.1.2.24:3306/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    url: jdbc:mysql://59.61.92.94:8883/fv?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: wlyy
    password: jkzlehr@123
---
spring:
  profiles: dev
  datasource:
    primaryReadWrite: #只读库 主库
      url: jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: root
      password: 123456
    primaryRead: #只读库 从库
      url: jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: root
      password: 123456
  redis:
    host: 172.19.103.47 # Redis server host.
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.19.103.77/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: root
    password: 123456

+ 1 - 1
patient-co-statistics/src/main/resources/quartz.properties

@ -13,7 +13,7 @@ org.quartz.threadPool.threadCount: 20
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
 
org.quartz.jobStore.misfireThreshold: 3600000
org.quartz.jobStore.misfireThreshold: 60000
 
#============================================================================
# Configure JobStore

+ 23 - 0
patient-co-wlyy/pom.xml

@ -243,6 +243,11 @@
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
@ -255,6 +260,24 @@
        </dependency>
        <!-- JSON end -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!-- LOGGING begin -->
        <dependency>
            <groupId>org.slf4j</groupId>

+ 7 - 11
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/dict/SystemDict.java

@ -1,10 +1,7 @@
package com.yihu.wlyy.entity.dict;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
/**
@ -21,7 +18,7 @@ public class SystemDict  implements java.io.Serializable {
	private String value;
	private String pyCode;
	private Integer sort;
	private String id;
	private Integer id;
	// Constructors
@ -36,15 +33,14 @@ public class SystemDict  implements java.io.Serializable {
		this.value = value;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return id;
	}
	public void setId(String id) {
	public void setId(Integer id) {
		this.id = id;
	}

+ 7 - 11
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/dict/SystemDictList.java

@ -1,10 +1,7 @@
package com.yihu.wlyy.entity.dict;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
/**
@ -25,7 +22,7 @@ public class SystemDictList   implements java.io.Serializable {
	private String relationColCode;
	private String relationColValue;
	private String relationColExtend;
	private String id;
	private Integer id;
	// Constructors
	/** default constructor */
@ -56,15 +53,14 @@ public class SystemDictList   implements java.io.Serializable {
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return id;
	}
	public void setId(String id) {
	public void setId(Integer id) {
		this.id = id;
	}

+ 10 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/doctor/profile/Doctor.java

@ -60,6 +60,7 @@ public class Doctor extends IdEntity {
	private String idcard;          //身份证号
	private Integer isFamous;       //是否是名医 1是  0或者空不是
	private String isPasswordPrompt;// 是否提示密码信息 1是 0或者空是否
	public Doctor() {}
@ -350,4 +351,13 @@ public class Doctor extends IdEntity {
    public boolean isHealthDoctor(){
        return level == 3;
    }
	@Column(name = "is_password_prompt")
	public String getIsPasswordPrompt() {
		return isPasswordPrompt;
	}
	public void setIsPasswordPrompt(String isPasswordPrompt) {
		this.isPasswordPrompt = isPasswordPrompt;
	}
}

+ 88 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/login/LoginLog.java

@ -0,0 +1,88 @@
package com.yihu.wlyy.entity.login;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Administrator on 2016.10.20.
 */
@Entity
@Table(name = "wlyy_login_log")
public class LoginLog  extends IdEntity {
    private String loginType;//1 短信登录  2 密码登录
    private String userCode;//登录用户主键 患者code或者医生code
    private String userType;//1 患者 2医生
    private Long tokenId;//登录的tokenid
    private String type;//登录成功1 成功 2失败
    private Date createTime;//创建时间
    private String errorMessage;//错误信息
    private String phone;//电话号码
    public String getLoginType() {
        return loginType;
    }
    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    public Long getTokenId() {
        return tokenId;
    }
    public void setTokenId(Long tokenId) {
        this.tokenId = tokenId;
    }
    public String getErrorMessage() {
        return errorMessage;
    }
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 53 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/PatientFamilyMember.java

@ -0,0 +1,53 @@
package com.yihu.wlyy.entity.patient;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 家庭成员表
 *
 * Created by lyr on 2016/10/17.
 */
@Entity
@Table(name = "wlyy_patient_family_member")
public class PatientFamilyMember extends IdEntity {
    // 居民cdoe
    private String patient;
    // 家庭成员
    private String familyMember;
    // 家庭关系
    private Integer familyRelation;
    // 操作日期
    private Date czrq;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getFamilyMember() {
        return familyMember;
    }
    public void setFamilyMember(String familyMember) {
        this.familyMember = familyMember;
    }
    public Integer getFamilyRelation() {
        return familyRelation;
    }
    public void setFamilyRelation(Integer familyRelation) {
        this.familyRelation = familyRelation;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 2 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamLogDao.java

@ -11,5 +11,6 @@ import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
public interface ConsultTeamLogDao extends PagingAndSortingRepository<ConsultTeamLog, Long>, JpaSpecificationExecutor<ConsultTeamLog> {
	
    int countByConsult(String consult);
}

+ 6 - 7
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorAdminTeamDao.java

@ -56,24 +56,23 @@ public interface DoctorAdminTeamDao extends
                                                 Pageable pageable);
    /**
     * 患者所签约团队。
     * 通过患者约团队取得行政团队。
     *
     * @param patientCode
     * @return
     */
    @Query("SELECT  t.id, t.name, t.leaderCode, d1.code, d1.name, d2.code, d2.name\n" +
            "FROM SignFamily f, Doctor d1, Doctor d2, AdminTeam t, AdminTeamMember m \n" +
            "WHERE d1.code = f.doctor AND f.doctorHealth = d2.code AND f.patient = :patientCode AND m.doctorCode = " +
            "d1.code AND m.teamId = t.id")
    Object getPatientSigningTeam(@Param("patientCode") String patientCode);
    @Query("SELECT t.id, t.name, t.leaderCode, f.doctor, f.doctorName, f.doctorHealth, f.doctorHealthName " +
            "FROM SignFamily f, AdminTeam t WHERE f.patient = :patientCode AND f.status in (-3, 1) AND t.id=f.adminTeamId ORDER BY f.czrq DESC")
    List<Object> findAdminTeamByPatientSignTeam(@Param("patientCode") String patientCode, Pageable pageable);
    @Query("SELECT t.id from AdminTeam t WHERE t.leaderCode = :leaderCode")
    Long findIdByLeaderCode(@Param("leaderCode") String leaderCode);
    @Query(" from AdminTeam t")
    List<AdminTeam> findAllTeam();
    @Query("SELECT t from AdminTeam t WHERE t.leaderCode = :leaderCode")
    AdminTeam findByLeaderCode(@Param("leaderCode") String leaderCode);
    List<AdminTeam> findByOrgCode(String orgCode);
}

+ 7 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorDao.java

@ -131,4 +131,11 @@ public interface DoctorDao extends PagingAndSortingRepository<Doctor, Long>, Jpa
    @Query("select p from Doctor p where p.isFamous=1 ")
    Page<Doctor> doctorFamousDoctorList(Pageable pageRequest);
    @Query("select p from Doctor p where p.idcard = ?1")
    Doctor findbyIdCard(String idcard);
    @Query("select d from Doctor d where d.del = 1 and d.password is null")
    List<Doctor> findAllNoPasswordDoctors();
}

+ 6 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamDao.java

@ -33,4 +33,10 @@ JpaSpecificationExecutor<DoctorTeam> {
	 */
	@Query("select dt from DoctorTeam dt,SignFamily sf  where dt.code=sf.teamCode and sf.type='2' and sf.status>=0 and sf.patient= ?1 and dt.del= '1'")
	DoctorTeam findByPatientCode(String patientCode);
	/**
	 * 通过患者获取家庭签约团队
	 */
	@Query("select dt from DoctorTeam dt,SignFamily sf  where dt.code=sf.teamCode and sf.type='1' and sf.status>=0 and sf.patient= ?1 and dt.del= '1'")
	DoctorTeam findSsTeamByPatientCode(String patientCode);
}

+ 4 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamMemberDao.java

@ -46,9 +46,12 @@ public interface DoctorTeamMemberDao extends PagingAndSortingRepository<DoctorTe
    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 ")
    @Query(" FROM DoctorTeamMember a WHERE a.team =?1 and  a.del='1' and  a.signType='2' and a.type = '3' and  a.memberCode=?2 ")
    DoctorTeamMember findMemberByTeamAndCode(String teamCode, String oldDoctorCode);
    @Query("select count(a) FROM DoctorTeamMember a WHERE a.team =?1 and  a.del='1' and  a.memberCode=?2 ")
    int countMemberByTeamAndCode(String teamCode, String oldDoctorCode);
    /**
     * 判断医生是否为三师签团队的成员。
     *

+ 12 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/login/LoginLogDao.java

@ -0,0 +1,12 @@
package com.yihu.wlyy.repository.login;
import com.yihu.wlyy.entity.login.LoginLog;
import com.yihu.wlyy.entity.message.SMS;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016.10.20.
 */
public interface LoginLogDao extends PagingAndSortingRepository<LoginLog, Long>, JpaSpecificationExecutor<LoginLog> {
}

+ 3 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/organization/HospitalDao.java

@ -40,4 +40,7 @@ public interface HospitalDao extends PagingAndSortingRepository<Hospital, Long>,
	@Query("select p from Hospital p where p.town = ?1 and p.del='1' and p.level =2 and p.centerSite='00'")
	List<Hospital> findByTownCode(String town);
	@Query("select p from Hospital p where p.city = ?1 and p.del='1' and p.level =2 and p.centerSite='00'")
	List<Hospital> findByCity(String city);
}

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

@ -51,4 +51,7 @@ public interface PatientDao extends PagingAndSortingRepository<Patient, Long> {
	@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 ")
	List<Patient> findAllIdCardPatientAndNoPassword();
}

+ 43 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientFamilyMemberDao.java

@ -0,0 +1,43 @@
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
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/17.
 */
public interface PatientFamilyMemberDao extends PagingAndSortingRepository<PatientFamilyMember, Long>,
        JpaSpecificationExecutor<PatientFamilyMember> {
    /**
     * 查询居民的某个成员
     *
     * @param patient 居民
     * @param member 成员
     * @return
     */
    PatientFamilyMember findByPatientAndFamilyMember(String patient,String member);
    /**
     * 查询居民的某个关系成员
     *
     * @param patient 居民
     * @param familyRelation 关系
     * @return
     */
    List<PatientFamilyMember> findByPatientAndFamilyRelation(String patient,Integer familyRelation);
    /**
     * 查找某个居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    List<PatientFamilyMember> findByPatient(String patient);
}

+ 13 - 6
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java

@ -22,14 +22,18 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
	@Query("select count(1) from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
	int hasSingStatus(String idcard);
	@Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
	SignFamily findByPatientStatus(String idcard, int status);
	@Modifying
	@Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1")
	int updatePatientMobile(String patient,String mobile);
    @Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
    SignFamily findByPatientStatus(String idcard, int status);
	@Query("select a from SignFamily a where a.patient = ?1 and status = ?2 and a.type = 2")
	SignFamily findByPatientCodeStatus(String patient, int status);
    @Query("select a from SignFamily a where a.patient = ?1 and status = ?2 and a.type = 2")
    SignFamily findByPatientCodeStatus(String patient, int status);
	@Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
	SignFamily findByPatientAndType(String patient,int type);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
    SignFamily findByPatientAndType(String patient,int type);
	SignFamily findByCode(String code);
@ -298,4 +302,7 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
	@Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 and a.id >= ?3 and a.id <= ?4 order by a.id")
	Page<SignFamily> findByTypeAndSignSourceAndId(Integer type,String signSource,Long start,Long end,Pageable pageable);
	@Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
	List<SignFamily> findAllSignByPatient(String patient);
}

+ 142 - 67
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java

@ -29,6 +29,8 @@ import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientSickDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -47,6 +49,8 @@ import org.springside.modules.persistence.SearchFilter.Operator;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.EncodesUtil;
import javax.print.Doc;
/**
 * 医生基本信息类.
 *
@ -83,8 +87,10 @@ public class DoctorInfoService extends BaseService {
    private ConsultDao consultDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    SMSService smsService;
    /**
     * 获取医生的签约病人
@ -92,7 +98,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public List<Object> getDoctorSignPatients(String doctor){
    public List<Object> getDoctorSignPatients(String doctor) {
        return signFamilyDao.findDoctorSignPatients(doctor);
    }
@ -102,8 +108,8 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public List<Object> getDoctorSignPatientsLikeName(String doctor,String patientName){
        return signFamilyDao.findDoctorSignPatientsLikeName(doctor,patientName);
    public List<Object> getDoctorSignPatientsLikeName(String doctor, String patientName) {
        return signFamilyDao.findDoctorSignPatientsLikeName(doctor, patientName);
    }
    /**
@ -112,8 +118,8 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public List<Object> getDoctorSignPatientsBySignType(String doctor,int type){
        return signFamilyDao.findDoctorSignPatientsBySignType(doctor,type);
    public List<Object> getDoctorSignPatientsBySignType(String doctor, int type) {
        return signFamilyDao.findDoctorSignPatientsBySignType(doctor, type);
    }
    /**
@ -122,8 +128,8 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public List<Object> getDoctorSignPatientsByTypeName(String doctor,int type,String patientName){
        return signFamilyDao.findDoctorSignPatientsByTypeName(doctor,type,patientName);
    public List<Object> getDoctorSignPatientsByTypeName(String doctor, int type, String patientName) {
        return signFamilyDao.findDoctorSignPatientsByTypeName(doctor, type, patientName);
    }
    public Doctor findDoctorByCode(String code) {
@ -197,7 +203,7 @@ public class DoctorInfoService extends BaseService {
    }
    public Page<Object> findPatientByDoctorSign(String doctor, long id,
                                                int pagesize, String patientName){
                                                int pagesize, String patientName) {
        // return doctorDao.findPatientByDoctorSign(doctor);
        Page<Object> signList = null;
@ -281,8 +287,8 @@ public class DoctorInfoService extends BaseService {
        if (StringUtils.isNotEmpty(query)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, query));
        }
        if(StringUtils.isNotEmpty(hospital)){
            hospital=hospital.substring(0,8);
        if (StringUtils.isNotEmpty(hospital)) {
            hospital = hospital.substring(0, 8);
            filters.put("hospital", new SearchFilter("hospital", Operator.LIKE,
                    hospital));
        }
@ -501,7 +507,7 @@ public class DoctorInfoService extends BaseService {
    }
    public List<Doctor> findDoctorByLevelAndHospital(String hospital, Integer level) {
        return doctorDao.findDoctorByLevelAndHospital(hospital,level);
        return doctorDao.findDoctorByLevelAndHospital(hospital, level);
    }
    /**
@ -511,9 +517,9 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public boolean updateDoctorIdcard(String idcard,String doctor) throws Exception {
    public boolean updateDoctorIdcard(String idcard, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if(doc == null){
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setIdcard(idcard);
@ -527,9 +533,9 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public boolean updateExpertise(String expertise,String doctor) throws Exception {
    public boolean updateExpertise(String expertise, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if(doc == null){
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setExpertise(expertise);
@ -543,9 +549,9 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public boolean updateSex(int sex,String doctor) throws Exception {
    public boolean updateSex(int sex, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if(doc == null){
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setSex(sex);
@ -559,9 +565,9 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    public boolean updateIntroduce(String introduce,String doctor) throws Exception {
    public boolean updateIntroduce(String introduce, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if(doc == null){
        if (doc == null) {
            throw new Exception("医生不存在");
        }
        doc.setIntroduce(introduce);
@ -570,19 +576,20 @@ public class DoctorInfoService extends BaseService {
    /**
     * 设置医生为名医
     *
     * @param doctorCode
     */
    @Transactional
    public void setFamous(String doctorCode,Integer status) {
        Doctor doctor=doctorDao.findByCode(doctorCode);
    public void setFamous(String doctorCode, Integer status) {
        Doctor doctor = doctorDao.findByCode(doctorCode);
        //如果是空或者大于1 默认是关闭名医
        if(status==null||status>1){
            status=0;
        if (status == null || status > 1) {
            status = 0;
        }
        doctor.setIsFamous(status);
    }
    public Page<Doctor> findDoctorByDept(String dept,String hosptial, String key, int page, int pageSize) {
    public Page<Doctor> findDoctorByDept(String dept, String hosptial, String key, int page, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
@ -609,7 +616,7 @@ public class DoctorInfoService extends BaseService {
        return doctorDao.findAll(spec, pageRequest);
    }
    public Page<Doctor> findFamousDoctor(String key,Integer type, int page, int pageSize,Integer level) {
    public Page<Doctor> findFamousDoctor(String key, Integer type, int page, int pageSize, Integer level) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
@ -623,12 +630,12 @@ public class DoctorInfoService extends BaseService {
        // 查询全部
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNotEmpty(key)) {
                filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, key));
            filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, key));
        }
        filters.put("isFamous", new SearchFilter("isFamous", SearchFilter.Operator.EQ, type));
        if(level!=null&&level>0&&level<4){
        if (level != null && level > 0 && level < 4) {
            filters.put("level", new SearchFilter("level", SearchFilter.Operator.EQ, level));
        }
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
@ -636,37 +643,29 @@ public class DoctorInfoService extends BaseService {
        return doctorDao.findAll(spec, pageRequest);
    }
    public void updateTeamHealthDoctor(String newDoctorCode, String oldDoctorCode, String patient)throws Exception {
    public void updateTeamHealthDoctor(String newDoctorCode, String oldDoctorCode, String patient) throws Exception {
        //得到患者的签约信息
        SignFamily signFamily= signFamilyDao.findByPatient(patient);
        String groupCode="";
        if(StringUtils.isNoneBlank(oldDoctorCode)){
            ConsultTeam consultTeam= consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patient,oldDoctorCode,2);
            if(consultTeam!=null){
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        String groupCode = "";
        if (StringUtils.isNoneBlank(oldDoctorCode)) {
            ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patient, oldDoctorCode, 2);
            if (consultTeam != null) {
                throw new Exception("存在没有关闭的健康咨询");
            }
            //修改医生服务团队 删除旧的健康管理师
            DoctorTeamMember doctorTeamMember=  doctorTeamDoctor.findMemberByTeamAndCode(signFamily.getTeamCode(),oldDoctorCode);
            doctorTeamMember.setDel("0");
            //把患者移除旧的健康管理师的患者表
            List<DoctorPatientGroupInfo>  oldDoctorPatientGroupInfos=doctorPatientGroupInfoDao.findByPatientAndDoctor(patient,oldDoctorCode);
            for(DoctorPatientGroupInfo doctorPatientGroupInfo:oldDoctorPatientGroupInfos){
                doctorPatientGroupInfo.setCzrq(new Date());
                doctorPatientGroupInfo.setStatus(0);//设置为无效
                //保存原来旧的分组
                if(Integer.valueOf(doctorPatientGroupInfo.getGroup())<4){
                    groupCode=doctorPatientGroupInfo.getGroup()+"";
                }
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findMemberByTeamAndCode(signFamily.getTeamCode(), oldDoctorCode);
            if (doctorTeamMember != null) {
                doctorTeamMember.setDel("0");
            }
        }
        Patient patientObj=patientDao.findByCode(patient);
        Doctor newD=doctorDao.findByCode(newDoctorCode);
        Patient patientObj = patientDao.findByCode(patient);
        Doctor newD = doctorDao.findByCode(newDoctorCode);
        //修改签约中的健康管理师
        signFamily.setDoctorHealth(newD.getCode());
        signFamily.setDoctorHealthName(newD.getName());
        //添加新的健康管理师到服务团队里
        DoctorTeamMember  newDoctorTeamMember=new DoctorTeamMember();
        DoctorTeamMember newDoctorTeamMember = new DoctorTeamMember();
        newDoctorTeamMember.setTeam(signFamily.getTeamCode());
        newDoctorTeamMember.setCzrq(new Date());
        newDoctorTeamMember.setName(newD.getName());
@ -674,27 +673,103 @@ public class DoctorInfoService extends BaseService {
        newDoctorTeamMember.setType(3);
        newDoctorTeamMember.setSignType("2");
        newDoctorTeamMember.setDel("1");
        newDoctorTeamMember.setCode(UUID.randomUUID().toString().replace("-",""));
        newDoctorTeamMember.setCode(UUID.randomUUID().toString().replace("-", ""));
        doctorTeamDoctor.save(newDoctorTeamMember);
    }
    public void updateTeamHealthDoctors(String newDoctorCode, String oldDoctorCode, String patients) throws Exception {
        String[] patiensString = patients.split(",");
        for (int i = 0; i < patiensString.length; i++) {
            updateTeamHealthDoctor(newDoctorCode, oldDoctorCode, patiensString[i]);
        }
    }
    /**
     * 医生更换手机号
     *
     * @param doctor  医生code
     * @param mobile  新手机号
     * @param captcha 验证码
     * @return
     */
    public int changeMobile(String doctor, String mobile, String captcha, int type) {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            return -1;
        }
        Doctor docMobile = doctorDao.findByMobile(mobile);
        if (docMobile != null && !docMobile.getCode().equals(doctor)) {
            return -2;
        }
        // 验证码验证
        int smsCheck = smsService.check(mobile, type == 1 ? 8 : 9, captcha);
        // 验证失败,不允许变更
        if (smsCheck != 1) {
            return -3;
        }
        doc.setMobile(mobile);
        //把患者加到新的健康管理师的患者表
        DoctorPatientGroupInfo doctorPatientGroupInfo = new DoctorPatientGroupInfo();
        doctorPatientGroupInfo.setCzrq(new Date());
        doctorPatientGroupInfo.setDoctor(newDoctorCode);
        doctorPatientGroupInfo.setStatus(1);
        doctorPatientGroupInfo.setPatient(patientObj.getCode());
        doctorPatientGroupInfo.setPname(patientObj.getName());
        doctorPatientGroupInfo.setPartAmount(0);
        doctorPatientGroupInfo.setGroup(groupCode);//默认健康分组
        doctorPatientGroupInfo.setQyrq(new Date());
        doctorPatientGroupInfo.setSignType("2");//家庭签约
        doctorPatientGroupInfoDao.save(doctorPatientGroupInfo);
    }
    public void updateTeamHealthDoctors(String newDoctorCode, String oldDoctorCode, String patients)throws Exception {
        String [] patiensString=patients.split(",");
        for (int i=0;i<patiensString.length;i++){
            updateTeamHealthDoctor(newDoctorCode,oldDoctorCode,patiensString[i]);
        return 1;
    }
    @Transactional
    public void updatePassword(String newPassword1, String newPassword2, String oldPassword, String doctorCode) throws Exception {
        if (!newPassword1.equals(newPassword2)) {
            throw new Exception("新密码不一致");
        }
        if (newPassword1.equals(oldPassword)) {
            throw new Exception("新旧密码一致");
        }
        Doctor doctor = doctorDao.findByCode(doctorCode);
        String oldPasswordTemp = MD5.GetMD5Code(oldPassword + doctor.getSalt());
        if (!oldPasswordTemp.equals(doctor.getPassword())) {
            throw new Exception("旧密码错误");
        }
        String newPassword1Temp = MD5.GetMD5Code(newPassword1 + doctor.getSalt());
        doctor.setPassword(newPassword1Temp);
    }
    /**
     * 查询患者是否与医生签约
     *
     * @param patient
     * @param doctor
     * @return
     */
    public boolean isPatientSigned(String patient, String doctor) {
        boolean bo = false;
        //签约团队
        DoctorTeam dt = doctorTeamDao.findByPatientCode(patient);
        DoctorTeam dtSS = doctorTeamDao.findSsTeamByPatientCode(patient);
        //医生是否属于团队成员
        if (dt != null && doctorTeamDoctor.countMemberByTeamAndCode(dt.getCode(), doctor) > 0) {
            bo = true;
        }
        if (dtSS != null && doctorTeamDoctor.countMemberByTeamAndCode(dtSS.getCode(), doctor) > 0) {
            bo = true;
        }
        return bo;
    }
    /**
     * 手机号是否注册
     *
     * @param mobile
     * @return
     */
    public int isMobileRegister(String mobile) {
        Doctor doc = doctorDao.findByMobile(mobile);
        if (doc != null) {
            return 1;
        } else {
            return 0;
        }
    }
}

+ 79 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java

@ -5,7 +5,9 @@ import com.yihu.wlyy.entity.address.Province;
import com.yihu.wlyy.entity.address.Street;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.demographic.DemographicInfo;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.repository.address.CityDao;
@ -15,7 +17,11 @@ import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.demographic.TblBasicDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -49,6 +55,62 @@ public class PatientInfoService extends BaseService {
	private TblBasicDao tblBasicDao;
	@Autowired
	private SocialSecurityInfoDao socialSecurityInfoDao;
	@Autowired
	SMSService smsService;
	@Autowired
	SignFamilyDao signFamilyDao;
	/**
	 * 患者更换手机号
	 *
	 * @param patient  患者code
	 * @param mobile  新手机号
	 * @param captcha 验证码
	 * @return
	 */
	public int changeMobile(String patient, String mobile, String captcha,int type) {
		Patient p = patientDao.findByCode(patient);
		if (p == null) {
			return -1;
		}
		Patient pMobile = patientDao.findByMobile(mobile);
		if (pMobile != null && !pMobile.getCode().equals(patient)) {
			return -2;
		}
		// 验证码验证
		int smsCheck = smsService.check(mobile, type == 1 ? 8 : 9, captcha);
		// 验证失败,不允许变更
		if (smsCheck != 1) {
			return -3;
		}
		p.setMobile(mobile);
		signFamilyDao.updatePatientMobile(p.getCode(),mobile);
		return 1;
	}
	/**
	 * 手机号是否注册
	 *
	 * @param mobile
	 * @return
	 */
	public int isMobileRegister(String mobile) {
		Patient p = patientDao.findByMobile(mobile);
		if (p != null) {
			return 1;
		} else {
			return 0;
		}
	}
	/**
	 * 根据患者标识查询患者信息
	 * @param code
@ -140,4 +202,21 @@ public class PatientInfoService extends BaseService {
			throw  new Exception("手机号已经被注册");
		}
	}
	@Transactional
	public void updatePassword(String newPassword1, String newPassword2, String oldPassword, String patientCode) throws Exception{
		if(!newPassword1.equals(newPassword2)){
			throw new Exception("新密码不一致");
		}
		if(newPassword1.equals(oldPassword)){
			throw new Exception("新旧密码一致");
		}
		Patient patient=patientDao.findByCode(patientCode);
		String oldPasswordTemp= MD5.GetMD5Code(oldPassword+patient.getSalt());
		if(!oldPasswordTemp.equals(patient.getPassword())){
			throw new Exception("旧密码错误");
		}
		String newPassword1Temp= MD5.GetMD5Code(newPassword1+patient.getSalt());
		patient.setPassword(newPassword1Temp);
	}
}

+ 20 - 6
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java

@ -223,7 +223,7 @@ public class ConsultTeamService extends ConsultService {
     * 根据状态获取三师家庭咨询
     *
     * @param doctor
     * @param status 0未处理或未回复 1已回复 2已结束
     * @param status   0未处理或未回复 1已回复 2已结束
     * @param id
     * @param pagesize
     * @return
@ -241,7 +241,7 @@ public class ConsultTeamService extends ConsultService {
        } else if (status == 1) {
            return findConsultByDoctorIng(doctor, id, pagesize);
        } else {
            return findByDoctorType4(doctor,id,pagesize);
            return findByDoctorType4(doctor, id, pagesize);
        }
    }
@ -530,6 +530,10 @@ public class ConsultTeamService extends ConsultService {
            DoctorTeam doctorTeam = doctorTeamDao.findBySanshiParientCode(patient);
            //得到团队的健康管理师
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 3);
            if (doctorTeamMember == null) {
                doctorTeamMember = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 2);
            }
            // 设置家庭医生
            ct.setDoctor(doctorTeamMember.getMemberCode());
            ct.setAdminTeamId(sc.getAdminTeamId());
@ -545,6 +549,11 @@ public class ConsultTeamService extends ConsultService {
            DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(patient);
            //得到团队的健康管理师
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 3);
            if (doctorTeamMember == null) {
                doctorTeamMember = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 2);
            }
            // 设置家庭医生
            ct.setDoctor(doctorTeamMember.getMemberCode());
            ct.setAdminTeamId(sf.getAdminTeamId());
@ -601,13 +610,13 @@ public class ConsultTeamService extends ConsultService {
        // 添加问题咨询日志
        String content = "";
        if(ct.getGuidance() > 0){
        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
            JSONObject json = guidanceService.findById(ct.getGuidance());
            if(json == null){
            if (json == null) {
                throw new Exception("guidance not exist");
            }
            content += "医生" + (json.get("doctorName") != null? json.get("doctorName").toString():"")
                    + "发出的指导:" + (json.getString("content") != null ? json.getString("content").toString() :"") + "<br/>";
            content += "医生" + (json.get("doctorName") != null ? json.get("doctorName").toString() : "")
                    + "发出的指导:" + (json.getString("content") != null ? json.getString("content").toString() : "") + "<br/>";
        }
        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
@ -762,6 +771,11 @@ public class ConsultTeamService extends ConsultService {
    public void transfer(String from, String to, String consult) {
        // 检查是否存在
        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
            ConsultTeam ct = consultTeamDao.findByConsult(consult);
            int count = consultTeamLogDao.countByConsult(consult);
            // 设置未读消息数
            ct.setDoctorRead(count);
            consultTeamDao.save(ct);
            // 查询医生信息
            Doctor d = doctorDao.findByCode(from);
            // 再保存

+ 19 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java

@ -151,8 +151,13 @@ public class PatientDeviceService extends BaseService {
		boolean bo = false;
		//签约团队
		DoctorTeam dt =doctorTeamDao.findByPatientCode(patientCode);
		DoctorTeam dtSS = doctorTeamDao.findSsTeamByPatientCode(patientCode);
		//医生是否属于团队成员
		if(dt!=null && doctorTeamMemberDao.findMemberByTeamAndCode(dt.getCode(),doctorCode)!=null)
		if(dt!=null && doctorTeamMemberDao.countMemberByTeamAndCode(dt.getCode(),doctorCode) > 0)
		{
			bo = true;
		}
		if(dtSS!=null && doctorTeamMemberDao.countMemberByTeamAndCode(dtSS.getCode(),doctorCode) > 0)
		{
			bo = true;
		}
@ -224,6 +229,19 @@ public class PatientDeviceService extends BaseService {
			}
		}
		re.sort(new Comparator<Map<String, Object>>() {
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0){
					return -1;
				}
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0){
					return 1;
				}
				return 0;
			}
		});
		return re;
	}

+ 382 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyMemberService.java

@ -0,0 +1,382 @@
package com.yihu.wlyy.service.app.family;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 家庭成员服务
 * <p>
 * Created by lyr on 2016/10/17.
 */
@Service
public class FamilyMemberService extends BaseService {
    @Autowired
    PatientFamilyMemberDao memberDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SMSService smsService;
    @Autowired
    private PatientInvitationLogDao patientInviteLogDao;
    @Autowired
    FamilyContractService contractService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    Map<Integer,String> relations = new HashMap<>();
    @PostConstruct
    public void init(){
        relations.put(0,"其他");
        relations.put(1,"父亲");
        relations.put(2,"母亲");
        relations.put(3,"老公");
        relations.put(4,"老婆");
        relations.put(5,"儿子");
        relations.put(6,"女儿");
    }
    /**
     * 添加家庭成员
     *
     * @param patient 患者
     * @param member  成员
     * @param captcha 验证码
     * @param member  成员
     * @return
     */
    public int addMember(String patient, String member, String captcha, String password, int relation) throws Exception {
        if (patient.equals(member)) {
            return 0;
        }
        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);
        if (p == null) {
            return -1;
        }
        // 添加的成员是否注册判断
        if (m == null) {
            return -2;
        }
        if(relation < 5) {
            List<PatientFamilyMember> familyMembers = memberDao.findByPatientAndFamilyRelation(patient, relation);
            if (familyMembers != null && familyMembers.size() > 0) {
                return -5;
            }
        }
        // 验证码验证
        if (StringUtils.isNotEmpty(captcha)) {
            int checkStatus = smsService.check(m.getMobile(), 10, captcha);
            if(checkStatus == -2){
                return -6;  // 验证码过期
            } else if(checkStatus == -1){
                return -3; // 验证码错误
            }
        }
        if (StringUtils.isNotEmpty(password)) {
            String loginPassword = MD5.GetMD5Code(password + m.getSalt());
            if (!loginPassword.equals(m.getPassword())) {
                return -3;
            }
        }
        // 添加自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        // 家庭关系已存在时,不重复添加
        if (fm != null) {
            return -4;
        } else {
            fm = new PatientFamilyMember();
            fm.setPatient(patient);
            fm.setFamilyMember(member);
        }
        fm.setFamilyRelation(relation);
        fm.setCzrq(new Date());
        // 添加对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);
        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(member);
            fmt.setFamilyMember(patient);
        }
        // 对方与自己的关系转换
        int relationTrans = familyRelationTrans(p, relation);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());
        memberDao.save(fm);
        memberDao.save(fmt);
        return 1;
    }
    /**
     * 修改家庭成员关系
     *
     * @param patient  居民
     * @param member   成员
     * @param relation 关系
     * @return
     */
    public int modifyFamilyRelation(String patient, String member, int relation) throws Exception {
        Patient p = patientDao.findByCode(patient);
        Patient m = patientDao.findByCode(member);
        if (p == null) {
            return -1;
        }
        // 成员是否注册判断
        if (m == null) {
            return -2;
        }
        // 自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        if (fm == null) {
            return -3;
        }
        fm.setFamilyRelation(relation);
        fm.setCzrq(new Date());
        // 对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);
        // 不存在则创建
        if (fmt == null) {
            fmt = new PatientFamilyMember();
            fmt.setPatient(patient);
            fmt.setFamilyMember(member);
        }
        int relationTrans = familyRelationTrans(p, relation);
        fmt.setFamilyRelation(relationTrans);
        fmt.setCzrq(new Date());
        memberDao.save(fm);
        memberDao.save(fmt);
        return 1;
    }
    /**
     * 删除家庭成员
     *
     * @param patient 居民
     * @param member  成员
     * @return
     */
    public int deleteMember(String patient, String member) {
        // 自己与对方的关系
        PatientFamilyMember fm = memberDao.findByPatientAndFamilyMember(patient, member);
        if (fm == null) {
            return -1;
        }
        // 对方与自己的关系
        PatientFamilyMember fmt = memberDao.findByPatientAndFamilyMember(member, patient);
        memberDao.delete(fm);
        if (fmt != null) {
            memberDao.delete(fmt);
        }
        return 1;
    }
    /**
     * 判断成员是否注册
     *
     * @param idcard 身份证号
     * @return
     */
    public JSONObject isRegister(String idcard, String patient) {
        JSONObject result = new JSONObject();
        Patient p = patientDao.findByIdcard(idcard);
        if (p == null) {
            result.put("isRegister", 0);
        } else {
            if (patient.equals(p.getCode())) {
                result.put("isRegister", -1); //不能添加自己
                return result;
            }
            result.put("isRegister", 1);
            result.put("mobile", StringUtils.isEmpty(p.getMobile()) ? "" : p.getMobile());
            result.put("name", StringUtils.isEmpty(p.getName()) ? "" : p.getName());
            result.put("code", StringUtils.isEmpty(p.getCode()) ? "" : p.getCode());
            result.put("photo", StringUtils.isEmpty(p.getPhoto()) ? "" : p.getPhoto());
        }
        return result;
    }
    /**
     * 获取居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientFamilyMembers(String patient, String doctorCode) {
        JSONArray resultArray = new JSONArray();
        String sql = "select * " +
                " from " +
                "    wlyy_patient_family_member t1, " +
                "    wlyy_patient t2 " +
                " where " +
                "    t2.code in (select family_member from wlyy_patient_family_member where patient = ? ) " +
                "    and t1.patient = ? " +
                "    and t1.family_member = t2.code ";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{patient, patient});
        if (result != null && result.size() > 0) {
            for (Map<String, Object> map : result) {
                JSONObject obj = new JSONObject();
                List<SignFamily> signs = contractService.findAllSignByPatient(map.get("code").toString());
                boolean ssSign = false;
                boolean jtSign = false;
                int status = 0;
                for (SignFamily sign : signs) {
                    if (sign.getType() == 1 && sign.getStatus() > 0) {
                        ssSign = true;
                        status = 3;
                    } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                        jtSign = true;
                        status = 3;
                    } else if (sign.getStatus() == 0) {
                        status = 2;
                    }
                }
                if (!StringUtils.isEmpty(doctorCode)) {
                    List<PatientInvitationLog> patientInviteLog = patientInviteLogDao.getPatientInviteLog(doctorCode,
                            patient, map.get("code").toString());
                    if (patientInviteLog != null && patientInviteLog.size() > 0 && status != 0) {
                        status = 1;
                    }
                }
                obj.put("code", map.get("code"));
                obj.put("name", map.get("name"));
                obj.put("sex", map.get("sex"));
                obj.put("birthday", map.get("birthday"));
                obj.put("idcard", StringUtils.isEmpty(String.valueOf(map.get("idcard"))) ? "" : map.get("idcard").toString());
                obj.put("photo", map.get("photo"));
                obj.put("mobile", map.get("mobile"));
                obj.put("address", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                obj.put("familyRelation", map.get("family_relation"));
                obj.put("familyRelationName", relations.get(map.get("family_relation")));
                if (!StringUtils.isEmpty(doctorCode)) {
                    obj.put("relaholder", relations.get(map.get("family_relation")));
                    obj.put("addressCode", "");
                    obj.put("addressName", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                    obj.put("status", status);
                    obj.put("source", 1);
                }
                if (ssSign && jtSign) {
                    obj.put("signType", 3);
                } else if (!ssSign && jtSign) {
                    obj.put("signType", 2);
                } else if (ssSign && !jtSign) {
                    obj.put("signType", 1);
                } else {
                    obj.put("signType", 0);
                }
                resultArray.put(obj);
            }
        }
        return resultArray;
    }
    /**
     * 家庭关系转换
     *
     * @param patient  居民
     * @param relation 关系 1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他
     * @return
     */
    public int familyRelationTrans(Patient patient, int relation) throws Exception {
        int relationTrans = 0;
        switch (relation) {
            case 1:
            case 2:
                if (patient.getSex() == 1) {
                    relationTrans = 5;
                } else if (patient.getSex() == 2) {
                    relationTrans = 6;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 6;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 5;
                    }
                }
                break;
            case 3:
                relationTrans = 4;
                break;
            case 4:
                relationTrans = 3;
                break;
            case 5:
            case 6:
                if (patient.getSex() == 1) {
                    relationTrans = 1;
                } else if (patient.getSex() == 2) {
                    relationTrans = 2;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 2;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 1;
                    }
                }
                break;
        }
        return relationTrans;
    }
}

+ 14 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyService.java

@ -17,6 +17,7 @@ import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.wechat.util.WeiXinTempMsgSendUtils;
import org.json.JSONArray;
@ -187,7 +188,12 @@ public class FamilyService {
                    if (!StringUtils.isEmpty(jo.get("name"))) {
                        patientTemp.setName(jo.get("name").toString());
                    }
                    patientTemp.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard(jo.get("idcard").toString())));
                    String idCardTemp=jo.get("idcard").toString();
                    String password=idCardTemp.substring(idCardTemp.length()-6);
                    String salt= UUID.randomUUID().toString().replace("-","");
                    patientTemp.setSalt(salt);
                    patientTemp.setPassword(MD5.GetMD5Code(password+salt));
                    patientTemp.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard_new(jo.get("idcard").toString())));
                    patientTemp.setBirthday(IdCardUtil.getBirthdayForIdcard(jo.get("idcard").toString()));
                    SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(jo.get("idcard").toString());
                    //设置医保卡号
@ -421,4 +427,11 @@ public class FamilyService {
            patientInvitationLog.setWxPushTime(new Date());
        }
    }
    public static void main(String[] args) {
        String idcard="350221195001210022";
        String password=idcard.substring(idcard.length()-6);
        String salt= "c89233bd15994b68ab3708ce79d5c2c4";
        System.out.println(MD5.GetMD5Code(password+salt));
    }
}

+ 1 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java

@ -48,6 +48,7 @@ public class PatientHealthGuidanceService extends BaseService {
			obj.put("doctorName",doc.getName());
			obj.put("patientName",p.getName());
			obj.put("czrq",guidance.getCzrq()!= null ? DateUtil.dateToStr(guidance.getCzrq(),DateUtil.YYYY_MM_DD_HH_MM) :"");
			return obj;
		}else{
			return null;

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

@ -49,725 +49,709 @@ import com.yihu.wlyy.util.SystemConf;
@Transactional(rollbackFor = Exception.class)
public class PatientHealthIndexService extends BaseService {
	private Clock clock = Clock.DEFAULT;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DevicePatientHealthIndexDao patientHealthIndexDao;
	@Autowired
	private PatientHealthStandardDao patientHealthStandardDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private SignFamilyDao signFamilyDao;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	/**
	 * 保存患者健康指标  (旧)
	 */
	public DevicePatientHealthIndex save(DevicePatientHealthIndex model, int index, double value, String patientCode) {
		model.setCzrq(clock.getCurrentDate());
		model.setDel("1");
		PatientHealthStandard standard = null;
		// 当前值/收缩压,正数为高,负数为低
		double value1 = 0;
		// 上次值/舒张压,正数为高,负数为低
		double value2 = 0;
		if (model.getType() == 1) {
			// 血糖记录,查询患者血糖预警值
			standard = patientHealthStandardDao.findByPatientType(model.getUser(), 1);
			if (index % 2 == 0) {
				// 餐后
				value1 = CommonUtil.checkHealthIndex(value, standard != null && standard.getMaxValue2() > 0 ? standard.getMaxValue2() : SystemConf.HEALTH_STANDARD_ST_MAX_AFTER, standard != null && standard.getMinValue2() > 0 ? standard.getMinValue2() : SystemConf.HEALTH_STANDARD_ST_MIN_AFTER);
			} else {
				// 餐前
				value1 = CommonUtil.checkHealthIndex(value, standard != null && standard.getMaxValue1() > 0 ? standard.getMaxValue1() : SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE, standard != null && standard.getMinValue1() > 0 ? standard.getMinValue1() : SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE);
			}
			// 查询上一次的血糖值
			if (value1 != 0) {
				value2 = NumberUtils.toDouble(findPreValue(model.getUser(), model.getType(), index, model.getRecordDate()), 0);
			}
		} else if (model.getType() == 2) {
			// 血压记录,查询患者血压预警值
			standard = patientHealthStandardDao.findByPatientType(model.getUser(), 2);
			// 收缩压
			value1 = CommonUtil.checkHealthIndex(NumberUtils.toDouble(model.getValue1(), 0), standard != null && standard.getMaxValue1() > 0 ? standard.getMaxValue1() : SystemConf.HEALTH_STANDARD_SSY_MAX, standard != null && standard.getMinValue1() > 0 ? standard.getMinValue1() : SystemConf.HEALTH_STANDARD_SSY_MIN);
			// 舒张压
			value2 = CommonUtil.checkHealthIndex(NumberUtils.toDouble(model.getValue2(), 0), standard != null && standard.getMaxValue2() > 0 ? standard.getMaxValue2() : SystemConf.HEALTH_STANDARD_SZY_MAX, standard != null && standard.getMinValue2() > 0 ? standard.getMinValue2() : SystemConf.HEALTH_STANDARD_SZY_MIN);
			if (value1 > 0 || value2 > 0) {
				value1 = NumberUtils.toDouble(model.getValue1(), 0);
				value2 = NumberUtils.toDouble(model.getValue2(), 0);
			} else if (value1 < 0 || value2 < 0) {
				value1 = -NumberUtils.toDouble(model.getValue1(), 0);
				value2 = -NumberUtils.toDouble(model.getValue2(), 0);
			}
		}
		// 保存到数据库
		model = patientHealthIndexDao.save(model);
		if (value1 != 0) {
			// 消息接收者
			List<String> receivers = new ArrayList<String>();
			// 查询患者信息
			Patient p = patientDao.findByCode(model.getUser());
			// 查询病人家庭签约的健康管理师
			SignFamily signFamily=signFamilyDao.findByjiatingPatientYes(p.getCode());
			String healthDoctorFamily ="";
			if(signFamily!=null){
				 healthDoctorFamily = signFamily.getDoctorHealth();
				if (StringUtils.isNotEmpty(healthDoctorFamily)) {
					// 添加到消息接收人列表
					receivers.add(healthDoctorFamily);
				}
			}
			// 查询病人三师签约中的健康管理师
			SignFamily signFamilySS=signFamilyDao.findBySanshiPatientYes(p.getCode());
			if(signFamilySS!=null){
				String healthDoctorTeam = signFamilySS.getDoctorHealth();
				// 判断是否是否是同一个健康管理师
				if (StringUtils.isNotEmpty(healthDoctorTeam) && !StringUtils.equals(healthDoctorFamily, healthDoctorTeam)) {
						// 添加到消息接收人列表
						receivers.add(healthDoctorTeam);
				}
			}
			List<Message> messages = new ArrayList<Message>();
			JSONArray array = new JSONArray();
			for (String receiver : receivers) {
				if (StringUtils.isEmpty(receiver)) {
					continue;
				}
				Patient patient=patientDao.findByCode(patientCode);
				// 保存异常消息
				Message message = new Message();
				message.setCzrq(new Date());
				message.setRead(1);
				message.setOver("1");
				message.setReceiver(receiver);
				message.setSender(p.getCode());
				message.setCode(getCode());
				message.setSex(patient.getSex());
				message.setSenderName(p.getName());
				message.setSenderPhoto(p.getPhoto());
				message.setTitle("预警值信息");
				String typeName="";
				switch (model.getType()){
					case 1:{typeName="血糖";break;}
					case 2:{typeName="血压";break;}
					case 3:{typeName="体重";break;}
					case 4:{typeName="腰围";break;}
				}
				message.setContent(patient.getName()+typeName+"超过预警值");
				message.setType(2);
				message.setValue1(value1);
				message.setValue2(value2);
				message.setTzCode(model.getId()+"");//消息关联的体征id
				message.setTzType(model.getType()+"");//体征类别 (1血糖,2血压,3体重,4腰围)
				messages.add(message);
				// 异常通知
				JSONObject json = new JSONObject();
				json.put("receiver", receiver);
				json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
				json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
				json.put("msg", p.getName() + "的体征指标出现异常,请及时处理!");
				json.put("data", "");
				array.put(json);
			}
			// 批量保存消息
			messageDao.save(messages);
			// 推送消息给医生
			PushMsgTask.getInstance().put(array);
		}
		return model;
	}
	/**
	 * 判断当前值是否在区间内
	 */
	private boolean checkHealthIndex(Double current,Double max,Double min)
	{
		if(current>max || current<min || current<0)
		{
			return false;
		}
		 return true;
	}
	/**
	 *推送信息
	 */
	private void sendMessage(String content, Patient patient,DevicePatientHealthIndex model)
	{
		String patientCode = patient.getCode();
		// 消息接收者
		List<String> receivers = new ArrayList<String>();
		// 查询病人家庭签约的健康管理师
		SignFamily signFamily=signFamilyDao.findByjiatingPatientYes(patientCode);
		String healthDoctorFamily ="";
		if(signFamily!=null){
			healthDoctorFamily = signFamily.getDoctorHealth();
			if (StringUtils.isNotEmpty(healthDoctorFamily)) {
				// 添加到消息接收人列表
				receivers.add(healthDoctorFamily);
			}
		}
		// 查询病人三师签约中的健康管理师
		SignFamily signFamilySS=signFamilyDao.findBySanshiPatientYes(patientCode);
		if(signFamilySS!=null){
			String healthDoctorTeam = signFamilySS.getDoctorHealth();
			// 判断是否是否是同一个健康管理师
			if (StringUtils.isNotEmpty(healthDoctorTeam) && !StringUtils.equals(healthDoctorFamily, healthDoctorTeam)) {
				// 添加到消息接收人列表
				receivers.add(healthDoctorTeam);
			}
		}
		List<Message> messages = new ArrayList<Message>();
		JSONArray array = new JSONArray();
		for (String receiver : receivers) {
			if (StringUtils.isEmpty(receiver)) {
				continue;
			}
			// 保存异常消息
			Message message = new Message();
			message.setCode(getCode());
			message.setCzrq(new Date());
			message.setRead(1);
			message.setOver("1");
			message.setReceiver(receiver);
			message.setSender(patientCode);
			message.setSex(patient.getSex());
			message.setSenderName(patient.getName());
			message.setSenderPhoto(patient.getPhoto());
			message.setTitle("预警值信息");
			message.setContent(content);
			message.setType(2);
			message.setValue1(Double.valueOf(model.getValue1()));
			message.setValue2(Double.valueOf(model.getValue2()));
			message.setTzCode(String.valueOf(model.getId()));//消息关联的体征id
			message.setTzType(String.valueOf(model.getType()));//体征类别 (1血糖,2血压,3体重,4腰围)
			messages.add(message);
			// 异常通知
			JSONObject json = new JSONObject();
			json.put("receiver", receiver);
			json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
			json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
			json.put("msg", content);
			json.put("data", "");
			array.put(json);
		}
		// 批量保存消息
		messageDao.save(messages);
		// 推送消息给医生
		PushMsgTask.getInstance().put(array);
	}
	/**
	 * 获取患者某天血糖值
	 * @return
    private Clock clock = Clock.DEFAULT;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private PatientHealthStandardDao patientHealthStandardDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    /**
     * 保存患者健康指标  (旧)
     */
	private DevicePatientHealthIndex getPatientXT(String patient,String dateString)
	{
		DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
		obj.setUser(patient);
		boolean hadData = false;
		Date date = DateUtil.strToDateShort(dateString);
		/***************** 按时间排序 ***************************/
		List<DevicePatientHealthIndex> list = patientHealthIndexDao.findByDate(patient,dateString);
		if(list!=null && list.size()>0)
		{
			obj.setType(1);
			obj.setCzrq(date);
			obj.setRecordDate(date);
			obj.setSortDate(date);
			for(DevicePatientHealthIndex item:list)
			{
				String data = item.getValue1();
				String dataType = item.getValue2();
				if(data!=null && dataType!=null) {
					if (dataType.equals("1")) {
						obj.setValue1(data);
						hadData = true;
					}
					else if(dataType.equals("2")) {
						obj.setValue2(data);
						hadData = true;
					}
					else if(dataType.equals("3")) {
						obj.setValue3(data);
						hadData = true;
					}
					else if(dataType.equals("4")) {
						obj.setValue4(data);
						hadData = true;
					}
					else if(dataType.equals("5")) {
						obj.setValue5(data);
						hadData = true;
					}
					else if(dataType.equals("6")) {
						obj.setValue6(data);
						hadData = true;
					}
					else if(dataType.equals("7")) {
						obj.setValue7(data);
						hadData = true;
					}
				}
			}
		}
		if(hadData)
		{
			return obj;
		}
		else{
			return null;
		}
	}
	/**
	 * 校验指标是否超标,发送消息
	 */
	public void verifyHealthIndex(Long id)
	{
		//指标信息
		DevicePatientHealthIndex data= patientHealthIndexDao.findOne(id);
		String patientCode = data.getUser();
		//患者信息
		Patient patient = patientDao.findByCode(patientCode);
		int type = data.getType();
		String msgContent = "";
		//血糖校验
		if(type == 1)
		{
			// 血糖记录,查询患者血糖预警值
			PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
			Double maxValueBefore =  SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
			Double minValueBefore =  SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
			Double maxValueAfter =  SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
			Double minValueAfter =  SystemConf.HEALTH_STANDARD_ST_MIN_AFTER;
			int index = Integer.valueOf(data.getValue2());
			String value1 = data.getValue1();
			// 餐后
			if (index % 2 == 0) {
				if(!checkHealthIndex(NumberUtils.toDouble(value1),maxValueBefore,minValueBefore)) {
					msgContent += patient.getName() + "饭后血糖超标,血糖值" + value1 + ",参考范围:" + minValueAfter + " ~ " + maxValueAfter + ";\n";
				}
			}
			else{ //餐前
				if(!checkHealthIndex(NumberUtils.toDouble(value1),maxValueAfter,minValueAfter)) {
					msgContent += patient.getName() + "饭前血糖超标,血糖值"+ value1+",参考范围:" + minValueBefore+" ~ "+  maxValueBefore+";\n";
				}
			}
		}
		//血压校验
		else if(type == 2)
		{
			String value1 = data.getValue1();
			String value2 = data.getValue2();
			// 血压记录,查询患者血压预警值
			PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
			Double maxValueSSY =  SystemConf.HEALTH_STANDARD_SSY_MAX;
			Double minValueSSY =  SystemConf.HEALTH_STANDARD_SSY_MIN;
			Double maxValueSZY =  SystemConf.HEALTH_STANDARD_SZY_MAX;
			Double minValueSZY =  SystemConf.HEALTH_STANDARD_SZY_MIN;
			if(standard!=null)
			{
				if(standard.getMaxValue1()>0)
				{
					maxValueSSY = standard.getMaxValue1();
				}
				if(standard.getMinValue1()>0)
				{
					minValueSSY = standard.getMinValue1();
				}
				if(standard.getMaxValue2()>0)
				{
					maxValueSZY = standard.getMaxValue2();
				}
				if(standard.getMinValue2()>0)
				{
					minValueSZY = standard.getMinValue2();
				}
			}
			// 收缩压校验
			if(!checkHealthIndex(NumberUtils.toDouble(value1),maxValueSSY,minValueSSY))
			{
				msgContent += "血压超标,收缩压"+ value1+",参考范围:" + minValueSSY+" ~ "+  maxValueSSY+";\n";
			}
			// 舒张压
			if(!checkHealthIndex(NumberUtils.toDouble(value2),maxValueSZY,minValueSZY))
			{
				msgContent += "血压超标,舒张压"+ value1+",参考范围:" + minValueSSY+" ~ "+  maxValueSSY+";\n";
			}
		}
		//超标则发送消息
		if(msgContent !=null && msgContent.length()>0)
		{
			sendMessage(msgContent,patient,data);
		}
	}
	/**
	 *新增患者指标
	 * 【血糖】{"time":"2016-09-09 17:00:00","gi":"血糖值(mmol/L)"}
	 * 【血压】{"time":"2016-09-09 17:00:00","sys":"收缩压(mmHg)","dia":"舒张压(mmHg)","pul":"脉搏(次/分)","ano":"有无心率不齐0否 1是","user":"身份标识"}
	 * 【体重】{"time":"2016-09-09 17:00:00","weight":"体重值(kg)"}
	 * 【腰围】{"time":"2016-09-09 17:00:00","waistline":"腰围值(cm)"}
	 * @return
    public DevicePatientHealthIndex save(DevicePatientHealthIndex model, int index, double value, String patientCode) {
        model.setCzrq(clock.getCurrentDate());
        model.setDel("1");
        PatientHealthStandard standard = null;
        // 当前值/收缩压,正数为高,负数为低
        double value1 = 0;
        // 上次值/舒张压,正数为高,负数为低
        double value2 = 0;
        if (model.getType() == 1) {
            // 血糖记录,查询患者血糖预警值
            standard = patientHealthStandardDao.findByPatientType(model.getUser(), 1);
            if (index % 2 == 0) {
                // 餐后
                value1 = CommonUtil.checkHealthIndex(value, standard != null && standard.getMaxValue2() > 0 ? standard.getMaxValue2() : SystemConf.HEALTH_STANDARD_ST_MAX_AFTER, standard != null && standard.getMinValue2() > 0 ? standard.getMinValue2() : SystemConf.HEALTH_STANDARD_ST_MIN_AFTER);
            } else {
                // 餐前
                value1 = CommonUtil.checkHealthIndex(value, standard != null && standard.getMaxValue1() > 0 ? standard.getMaxValue1() : SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE, standard != null && standard.getMinValue1() > 0 ? standard.getMinValue1() : SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE);
            }
            // 查询上一次的血糖值
            if (value1 != 0) {
                value2 = NumberUtils.toDouble(findPreValue(model.getUser(), model.getType(), index, model.getRecordDate()), 0);
            }
        } else if (model.getType() == 2) {
            // 血压记录,查询患者血压预警值
            standard = patientHealthStandardDao.findByPatientType(model.getUser(), 2);
            // 收缩压
            value1 = CommonUtil.checkHealthIndex(NumberUtils.toDouble(model.getValue1(), 0), standard != null && standard.getMaxValue1() > 0 ? standard.getMaxValue1() : SystemConf.HEALTH_STANDARD_SSY_MAX, standard != null && standard.getMinValue1() > 0 ? standard.getMinValue1() : SystemConf.HEALTH_STANDARD_SSY_MIN);
            // 舒张压
            value2 = CommonUtil.checkHealthIndex(NumberUtils.toDouble(model.getValue2(), 0), standard != null && standard.getMaxValue2() > 0 ? standard.getMaxValue2() : SystemConf.HEALTH_STANDARD_SZY_MAX, standard != null && standard.getMinValue2() > 0 ? standard.getMinValue2() : SystemConf.HEALTH_STANDARD_SZY_MIN);
            if (value1 > 0 || value2 > 0) {
                value1 = NumberUtils.toDouble(model.getValue1(), 0);
                value2 = NumberUtils.toDouble(model.getValue2(), 0);
            } else if (value1 < 0 || value2 < 0) {
                value1 = -NumberUtils.toDouble(model.getValue1(), 0);
                value2 = -NumberUtils.toDouble(model.getValue2(), 0);
            }
        }
        // 保存到数据库
        model = patientHealthIndexDao.save(model);
        if (value1 != 0) {
            // 消息接收者
            List<String> receivers = new ArrayList<String>();
            // 查询患者信息
            Patient p = patientDao.findByCode(model.getUser());
            // 查询病人家庭签约的健康管理师
            SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(p.getCode());
            String healthDoctorFamily = "";
            if (signFamily != null) {
                healthDoctorFamily = signFamily.getDoctorHealth();
                if (StringUtils.isNotEmpty(healthDoctorFamily)) {
                    // 添加到消息接收人列表
                    receivers.add(healthDoctorFamily);
                }
            }
            // 查询病人三师签约中的健康管理师
            SignFamily signFamilySS = signFamilyDao.findBySanshiPatientYes(p.getCode());
            if (signFamilySS != null) {
                String healthDoctorTeam = signFamilySS.getDoctorHealth();
                // 判断是否是否是同一个健康管理师
                if (StringUtils.isNotEmpty(healthDoctorTeam) && !StringUtils.equals(healthDoctorFamily, healthDoctorTeam)) {
                    // 添加到消息接收人列表
                    receivers.add(healthDoctorTeam);
                }
            }
            List<Message> messages = new ArrayList<Message>();
            JSONArray array = new JSONArray();
            for (String receiver : receivers) {
                if (StringUtils.isEmpty(receiver)) {
                    continue;
                }
                Patient patient = patientDao.findByCode(patientCode);
                // 保存异常消息
                Message message = new Message();
                message.setCzrq(new Date());
                message.setRead(1);
                message.setOver("1");
                message.setReceiver(receiver);
                message.setSender(p.getCode());
                message.setCode(getCode());
                message.setSex(patient.getSex());
                message.setSenderName(p.getName());
                message.setSenderPhoto(p.getPhoto());
                message.setTitle("预警值信息");
                String typeName = "";
                switch (model.getType()) {
                    case 1: {
                        typeName = "血糖";
                        break;
                    }
                    case 2: {
                        typeName = "血压";
                        break;
                    }
                    case 3: {
                        typeName = "体重";
                        break;
                    }
                    case 4: {
                        typeName = "腰围";
                        break;
                    }
                }
                message.setContent(patient.getName() + typeName + "超过预警值");
                message.setType(2);
                message.setValue1(value1);
                message.setValue2(value2);
                message.setTzCode(model.getId() + "");//消息关联的体征id
                message.setTzType(model.getType() + "");//体征类别 (1血糖,2血压,3体重,4腰围)
                messages.add(message);
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", receiver);
                json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
                json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
                json.put("msg", p.getName() + "的体征指标出现异常,请及时处理!");
                json.put("data", "");
                array.put(json);
            }
            // 批量保存消息
            messageDao.save(messages);
            // 推送消息给医生
            PushMsgTask.getInstance().put(array);
        }
        return model;
    }
    /**
     * 判断当前值是否在区间内
     */
	public DevicePatientHealthIndex addPatientHealthIndex(String data,String type,String patientCode,String deviceSn) throws Exception
	{
		Map<String,String> map = (Map<String,String>)objectMapper.readValue(data,Map.class);
		DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
		Date currentTime = new Date();
		obj.setCzrq(currentTime);
		obj.setDel("1");
		Date time = currentTime;
		if (map.containsKey("time")) {
			time = DateUtil.strToDateLong(map.get("time"));
		}
		obj.setRecordDate(time);    //记录时间
		obj.setSortDate(time);      //排序时间
		String idcard = "";
		Patient patient = null;
		if(deviceSn!=null && deviceSn.length()>0)   //设备数据
		{
			obj.setDeviceSn(deviceSn);
			String userType = "-1";
			if(map.containsKey("user")) { //存在身份标识 ,多用户
				userType = map.get("user");
			}
			//根据设备获取患者(不同厂家sn码一样的问题未解决!!)
			PatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn,type,userType);
			if(device!=null)
			{
				patientCode = device.getUser();
				patient = patientDao.findByCode(patientCode);
				idcard = device.getUserIdcard();
			}
		}
		//自输数据
		else{
			patient = patientDao.findByCode(patientCode);
			if(patient!=null) {
				idcard = patient.getIdcard();
			}
		}
		//身份证不为空
		if(patient!=null) {
			obj.setUser(patientCode);
			obj.setIdcard(idcard);
			String msgContent = "";
			// 1血糖 2血压 3体重 4腰围
			switch (type) {
				case "1": {
					obj.setType(1);
					String value1 = map.get("gi");  //血糖值
					String value2 = map.get("gi_type");  //血糖值类型
					obj.setValue1(value1);
					obj.setValue2(value2);
					break;
				}
				case "2":{
					obj.setType(2);
					String value1 = map.get("sys");  //收缩压
					String value2 = map.get("dia");  //舒张压
					obj.setValue1(value1);
					obj.setValue2(value2);
					obj.setValue3(map.get("pul"));     //脉搏
					obj.setValue4(map.get("ano"));     //有无心率不齐
					break;
				}
				case "3":
				{
					obj.setType(3);
					obj.setValue1(map.get("weight")); //体重
					break;
				}
				case "4":{
					obj.setType(4);
					obj.setValue1(map.get("waistline"));  //腰围
					break;
				}
				default: {
					throw new Exception("暂不支持该指标!");
				}
			}
			patientHealthIndexDao.save(obj);
		}
		else{
			throw new Exception("不存在该患者!");
		}
		return obj;
	}
	/**
	 * 按录入时间和患者标识查询健康记录
	 * @param patientCode
	 * @param date
	 * @return
	 */
	public Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date) {
		return patientHealthIndexDao.findByPatienDate(patientCode, type, date);
	}
	/**
	 * 按时间段查询患者健康指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @param begin 开始时间
	 * @param end 结束时间
	 * @return
	 */
	public List<DevicePatientHealthIndex> findChartByPatien(String patient, int type, String begin, String end) {
		List<DevicePatientHealthIndex> re = new ArrayList<>();
		Date startDate =  DateUtil.strToDate(begin,DateUtil.YYYY_MM_DD_HH_MM_SS);
		Date endDate = DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS);
		if(type == 1)   //血糖特殊处理
		{
			//根据时间过滤排序
			List<String>  dateList = patientHealthIndexDao.findDateList(patient,startDate,endDate,null);
			if(dateList!=null && dateList.size()>0)
			{
				for(int i=dateList.size()-1;i>=0;i--)
				{
					String dateString = dateList.get(i);
					DevicePatientHealthIndex obj = getPatientXT(patient,dateString);
					if(obj!=null)
					{
						re.add(obj);
					}
				}
			}
		}
		else{
			// 排序
			Sort sort = new Sort(Direction.ASC, "recordDate");
			PageRequest pageRequest = new PageRequest(0,100,sort);
			re = patientHealthIndexDao.findIndexByPatient(patient, type, startDate, endDate,null).getContent();
		}
		return re;
	}
	/**
	 * 查询指标记录
	 *
	 * @param patient
	 * @param type
	 * @param start
	 * @param end
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, String start,String end,int page, int pageSize){
		List<DevicePatientHealthIndex> re = new ArrayList<>();
		if(page > 0) {
			page = page -1;
		}
		Date startDate =  DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS);
		Date endDate = DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS);
		if(type == 1)   //血糖特殊处理
		{
			PageRequest pageRequest = new PageRequest(page,pageSize);
			//根据时间过滤排序
			List<String>  dateList = patientHealthIndexDao.findDateList(patient,startDate,endDate,pageRequest);
			if(dateList!=null && dateList.size()>0)
			{
				for(String dateString : dateList)
				{
					DevicePatientHealthIndex obj = getPatientXT(patient,dateString);
					if(obj!=null)
					{
						re.add(obj);
					}
				}
			}
		}
		else{
			// 排序
			Sort sort = new Sort(Direction.DESC, "recordDate");
			PageRequest pageRequest = new PageRequest(page,pageSize,sort);
			Page<DevicePatientHealthIndex>  list= patientHealthIndexDao.findIndexByPatient(patient,type,startDate,endDate,pageRequest);
			re = list.getContent();
		}
		return re;
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patientCode 患者标志
	 * @param pageSize 页数
	 * @return 健康指标列表
	 */
	public Page<DevicePatientHealthIndex> findByPatien(String patientCode, int type, Date sortDate, Date begin, Date end, int pageSize) {
		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "sortDate");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		// 患者标志
		filters.put("user", new SearchFilter("user", Operator.EQ, patientCode));
		if (sortDate != null) {
			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
		}
		filters.put("recordDate1", new SearchFilter("recordDate", Operator.GTE, begin));
		filters.put("recordDate2", new SearchFilter("recordDate", Operator.LTE, end));
		filters.put("type", new SearchFilter("type", Operator.EQ, type));
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<DevicePatientHealthIndex> spec = DynamicSpecifications.bySearchFilter(filters.values(), DevicePatientHealthIndex.class);
		return patientHealthIndexDao.findAll(spec, pageRequest);
	}
	/**
	 * 查询患者健康指标预警值
	 * @param patient
	 * @return
	 */
	public Iterable<PatientHealthStandard> findStandardByPatient(String patient) {
		return patientHealthStandardDao.findByPatient(patient);
	}
	/**
	 * 保存患者健康指标预警值
	 * @param list
	 */
	public Iterable<PatientHealthStandard> saveStandard(List<PatientHealthStandard> list, String patient) {
		// 先删除
		patientHealthStandardDao.deleteByPatient(patient);
		return patientHealthStandardDao.save(list);
	}
	/**
	 * 查询患者最近填写的运动、用药、饮食内容
	 * @param patient
	 * @return
	 */
	public JSONArray findRecentByPatient(String patient) {
		JSONArray array = new JSONArray();
		Iterable<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
		if (iterable != null) {
			Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
			while (iterator != null && iterator.hasNext()) {
				DevicePatientHealthIndex phi = iterator.next();
				if (phi == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 设置健康指标类型(1血糖,2血压,3体重,4腰围)
				json.put("type", phi.getType());
				// 设置血糖/收缩压/体重/腰围/早餐前空腹
				json.put("value1", phi.getValue1());
				// 设置舒张压/早餐后血糖
				json.put("value2", phi.getValue2());
				// 设置午餐前血糖
				json.put("value3", phi.getValue3());
				// 设置午餐后血糖
				json.put("value4", phi.getValue4());
				// 设置晚餐前血糖
				json.put("value5", phi.getValue5());
				// 设置晚餐后血糖
				json.put("value6", phi.getValue6());
				// 设置睡前血糖
				json.put("value7", phi.getValue7());
				json.put("date", DateUtil.dateToStrShort(phi.getRecordDate()));
				array.put(json);
			}
		}
		return array;
	}
	/**
	 * 查询上一次的值
	 * @param patient 患者标识
	 * @param type 类型:1血糖,2血压
	 * @param index 第几个值,1~7
	 * @return
	 */
	private String findPreValue(String patient, int type, int index, Date recordDate) {
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, 1);
		Page<String> page = null;
		switch (index) {
		case 1:
			page = patientHealthIndexDao.findValue1ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 2:
			page = patientHealthIndexDao.findValue2ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 3:
			page = patientHealthIndexDao.findValue3ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 4:
			page = patientHealthIndexDao.findValue4ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 5:
			page = patientHealthIndexDao.findValue5ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 6:
			page = patientHealthIndexDao.findValue6ByPatient(patient, type, recordDate, pageRequest);
			break;
		case 7:
			page = patientHealthIndexDao.findValue7ByPatient(patient, type, recordDate, pageRequest);
			break;
		}
		if (page != null && page.getNumberOfElements() > 0) {
			return page.getContent().get(0);
		}
		return "0";
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patientCode 患者标志
	 * @return 健康指标列表
	 */
	public DevicePatientHealthIndex findLastByPatien(String patientCode,int type) {
		//最新血糖指标
		if(type == 1)
		{
			DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode,1);
			if(obj!=null)
			{
				String dateString =DateUtil.dateToStrShort(obj.getRecordDate());
				return getPatientXT(patientCode,dateString);
			}
			else{
				return null;
			}
		}
		else{  //其他指标
		   return patientHealthIndexDao.findLastData(patientCode,2);
		}
	}
    private boolean checkHealthIndex(Double current, Double max, Double min) {
        if (current > max || current < min || current < 0) {
            return false;
        }
        return true;
    }
    /**
     * 推送信息
     */
    private void sendMessage(String content, Patient patient, DevicePatientHealthIndex model) {
        String patientCode = patient.getCode();
        // 消息接收者
        List<String> receivers = new ArrayList<String>();
        // 查询病人家庭签约的健康管理师
        SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(patientCode);
        String healthDoctorFamily = "";
        if (signFamily != null) {
            healthDoctorFamily = signFamily.getDoctorHealth();
            if (StringUtils.isNotEmpty(healthDoctorFamily)) {
                // 添加到消息接收人列表
                receivers.add(healthDoctorFamily);
            } else {
                // 添加到消息接收人列表
                receivers.add(signFamily.getDoctor());
            }
        }
        // 查询病人三师签约中的健康管理师
        SignFamily signFamilySS = signFamilyDao.findBySanshiPatientYes(patientCode);
        if (signFamilySS != null) {
            String healthDoctorTeam = StringUtils.isNotEmpty(signFamilySS.getDoctorHealth()) ? signFamilySS.getDoctorHealth() : signFamilySS.getDoctor();
            // 判断是否是否是同一个健康管理师
            if (StringUtils.isNotEmpty(healthDoctorTeam) && !StringUtils.equals(healthDoctorFamily, healthDoctorTeam)) {
                // 添加到消息接收人列表
                receivers.add(healthDoctorTeam);
            }
        }
        List<Message> messages = new ArrayList<Message>();
        JSONArray array = new JSONArray();
        for (String receiver : receivers) {
            if (StringUtils.isEmpty(receiver)) {
                continue;
            }
            // 保存异常消息
            Message message = new Message();
            message.setCode(getCode());
            message.setCzrq(new Date());
            message.setRead(1);
            message.setOver("1");
            message.setReceiver(receiver);
            message.setSender(patientCode);
            message.setSex(patient.getSex());
            message.setSenderName(patient.getName());
            message.setSenderPhoto(patient.getPhoto());
            message.setTitle("预警值信息");
            message.setContent(content);
            message.setType(2);
            message.setValue1(Double.valueOf(model.getValue1()));
            message.setValue2(Double.valueOf(model.getValue2()));
            message.setTzCode(String.valueOf(model.getId()));//消息关联的体征id
            message.setTzType(String.valueOf(model.getType()));//体征类别 (1血糖,2血压,3体重,4腰围)
            messages.add(message);
            // 异常通知
            JSONObject json = new JSONObject();
            json.put("receiver", receiver);
            json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
            json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
            json.put("msg", content);
            json.put("data", "");
            array.put(json);
        }
        // 批量保存消息
        messageDao.save(messages);
        // 推送消息给医生
        PushMsgTask.getInstance().put(array);
    }
    /**
     * 获取患者某天血糖值
     *
     * @return
     */
    private DevicePatientHealthIndex getPatientXT(String patient, String dateString) {
        DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
        obj.setUser(patient);
        boolean hadData = false;
        Date date = DateUtil.strToDateShort(dateString);
        /***************** 按时间排序 ***************************/
        List<DevicePatientHealthIndex> list = patientHealthIndexDao.findByDate(patient, dateString);
        if (list != null && list.size() > 0) {
            obj.setType(1);
            obj.setCzrq(date);
            obj.setRecordDate(date);
            obj.setSortDate(date);
            for (DevicePatientHealthIndex item : list) {
                String data = item.getValue1();
                String dataType = item.getValue2();
                if (data != null && dataType != null) {
                    if (dataType.equals("1")) {
                        obj.setValue1(data);
                        hadData = true;
                    } else if (dataType.equals("2")) {
                        obj.setValue2(data);
                        hadData = true;
                    } else if (dataType.equals("3")) {
                        obj.setValue3(data);
                        hadData = true;
                    } else if (dataType.equals("4")) {
                        obj.setValue4(data);
                        hadData = true;
                    } else if (dataType.equals("5")) {
                        obj.setValue5(data);
                        hadData = true;
                    } else if (dataType.equals("6")) {
                        obj.setValue6(data);
                        hadData = true;
                    } else if (dataType.equals("7")) {
                        obj.setValue7(data);
                        hadData = true;
                    }
                }
            }
        }
        if (hadData) {
            return obj;
        } else {
            return null;
        }
    }
    /**
     * 校验指标是否超标,发送消息
     */
    public void verifyHealthIndex(Long id) {
        //指标信息
        DevicePatientHealthIndex data = patientHealthIndexDao.findOne(id);
        String patientCode = data.getUser();
        //患者信息
        Patient patient = patientDao.findByCode(patientCode);
        int type = data.getType();
        String msgContent = "";
        //血糖校验
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = SystemConf.HEALTH_STANDARD_ST_MIN_AFTER;
            int index = Integer.valueOf(data.getValue2());
            String value1 = data.getValue1();
            // 餐后
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    msgContent += patient.getName() + "饭后血糖超标,血糖值" + value1 + ",参考范围:" + minValueAfter + " ~ " + maxValueAfter + ";\n";
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    msgContent += patient.getName() + "饭前血糖超标,血糖值" + value1 + ",参考范围:" + minValueBefore + " ~ " + maxValueBefore + ";\n";
                }
            }
        }
        //血压校验
        else if (type == 2) {
            String value1 = data.getValue1();
            String value2 = data.getValue2();
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = SystemConf.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = SystemConf.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            // 收缩压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)) {
                msgContent += "血压超标,收缩压" + value1 + ",参考范围:" + minValueSSY + " ~ " + maxValueSSY + ";\n";
            }
            // 舒张压
            if (!checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                msgContent += "血压超标,舒张压" + value1 + ",参考范围:" + minValueSSY + " ~ " + maxValueSSY + ";\n";
            }
        }
        //超标则发送消息
        if (msgContent != null && msgContent.length() > 0) {
            sendMessage(msgContent, patient, data);
        }
    }
    /**
     * 新增患者指标
     * 【血糖】{"time":"2016-09-09 17:00:00","gi":"血糖值(mmol/L)"}
     * 【血压】{"time":"2016-09-09 17:00:00","sys":"收缩压(mmHg)","dia":"舒张压(mmHg)","pul":"脉搏(次/分)","ano":"有无心率不齐0否 1是","user":"身份标识"}
     * 【体重】{"time":"2016-09-09 17:00:00","weight":"体重值(kg)"}
     * 【腰围】{"time":"2016-09-09 17:00:00","waistline":"腰围值(cm)"}
     *
     * @return
     */
    public DevicePatientHealthIndex addPatientHealthIndex(String data, String type, String patientCode, String deviceSn) throws Exception {
        Map<String, String> map = (Map<String, String>) objectMapper.readValue(data, Map.class);
        DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
        Date currentTime = new Date();
        obj.setCzrq(currentTime);
        obj.setDel("1");
        Date time = currentTime;
        if (map.containsKey("time")) {
            time = DateUtil.strToDateLong(map.get("time"));
        }
        obj.setRecordDate(time);    //记录时间
        obj.setSortDate(time);      //排序时间
        String idcard = "";
        Patient patient = null;
        if (deviceSn != null && deviceSn.length() > 0)   //设备数据
        {
            obj.setDeviceSn(deviceSn);
            String userType = "-1";
            if (map.containsKey("user")) { //存在身份标识 ,多用户
                userType = map.get("user");
            }
            //根据设备获取患者(不同厂家sn码一样的问题未解决!!)
            PatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
            if (device != null) {
                patientCode = device.getUser();
                patient = patientDao.findByCode(patientCode);
                idcard = device.getUserIdcard();
            }
        }
        //自输数据
        else {
            patient = patientDao.findByCode(patientCode);
            if (patient != null) {
                idcard = patient.getIdcard();
            }
        }
        //身份证不为空
        if (patient != null) {
            obj.setUser(patientCode);
            obj.setIdcard(idcard);
            String msgContent = "";
            // 1血糖 2血压 3体重 4腰围
            switch (type) {
                case "1": {
                    obj.setType(1);
                    String value1 = map.get("gi");  //血糖值
                    String value2 = map.get("gi_type");  //血糖值类型
                    obj.setValue1(value1);
                    obj.setValue2(value2);
                    break;
                }
                case "2": {
                    obj.setType(2);
                    String value1 = map.get("sys");  //收缩压
                    String value2 = map.get("dia");  //舒张压
                    obj.setValue1(value1);
                    obj.setValue2(value2);
                    obj.setValue3(map.get("pul"));     //脉搏
                    obj.setValue4(map.get("ano"));     //有无心率不齐
                    break;
                }
                case "3": {
                    obj.setType(3);
                    obj.setValue1(map.get("weight")); //体重
                    break;
                }
                case "4": {
                    obj.setType(4);
                    obj.setValue1(map.get("waistline"));  //腰围
                    break;
                }
                default: {
                    throw new Exception("暂不支持该指标!");
                }
            }
            patientHealthIndexDao.save(obj);
        } else {
            throw new Exception("不存在该患者!");
        }
        return obj;
    }
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @param patientCode
     * @param date
     * @return
     */
    public Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date) {
        return patientHealthIndexDao.findByPatienDate(patientCode, type, date);
    }
    /**
     * 按时间段查询患者健康指标
     *
     * @param type  健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public List<DevicePatientHealthIndex> findChartByPatien(String patient, int type, String begin, String end) {
        List<DevicePatientHealthIndex> re = new ArrayList<>();
        Date startDate = DateUtil.strToDate(begin, DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
        if (type == 1)   //血糖特殊处理
        {
            //根据时间过滤排序
            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, null);
            if (dateList != null && dateList.size() > 0) {
                for (int i = dateList.size() - 1; i >= 0; i--) {
                    String dateString = dateList.get(i);
                    DevicePatientHealthIndex obj = getPatientXT(patient, dateString);
                    if (obj != null) {
                        re.add(obj);
                    }
                }
            }
        } else {
            // 排序
            Sort sort = new Sort(Direction.ASC, "recordDate");
            PageRequest pageRequest = new PageRequest(0, 100, sort);
            re = patientHealthIndexDao.findIndexByPatient(patient, type, startDate, endDate, null).getContent();
        }
        return re;
    }
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    public List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, String start, String end, int page, int pageSize) {
        List<DevicePatientHealthIndex> re = new ArrayList<>();
        if (page > 0) {
            page = page - 1;
        }
        Date startDate = DateUtil.strToDate(start, DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = new PageRequest(page, pageSize);
            //根据时间过滤排序
            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest);
            if (dateList != null && dateList.size() > 0) {
                for (String dateString : dateList) {
                    DevicePatientHealthIndex obj = getPatientXT(patient, dateString);
                    if (obj != null) {
                        re.add(obj);
                    }
                }
            }
        } else {
            // 排序
            Sort sort = new Sort(Direction.DESC, "recordDate");
            PageRequest pageRequest = new PageRequest(page, pageSize, sort);
            Page<DevicePatientHealthIndex> list = patientHealthIndexDao.findIndexByPatient(patient, type, startDate, endDate, pageRequest);
            re = list.getContent();
        }
        return re;
    }
    /**
     * 根据患者标志获取健康指标
     *
     * @param patientCode 患者标志
     * @param pageSize    页数
     * @return 健康指标列表
     */
    public Page<DevicePatientHealthIndex> findByPatien(String patientCode, int type, Date sortDate, Date begin, Date end, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "sortDate");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 患者标志
        filters.put("user", new SearchFilter("user", Operator.EQ, patientCode));
        if (sortDate != null) {
            filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
        }
        filters.put("recordDate1", new SearchFilter("recordDate", Operator.GTE, begin));
        filters.put("recordDate2", new SearchFilter("recordDate", Operator.LTE, end));
        filters.put("type", new SearchFilter("type", Operator.EQ, type));
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<DevicePatientHealthIndex> spec = DynamicSpecifications.bySearchFilter(filters.values(), DevicePatientHealthIndex.class);
        return patientHealthIndexDao.findAll(spec, pageRequest);
    }
    /**
     * 查询患者健康指标预警值
     *
     * @param patient
     * @return
     */
    public Iterable<PatientHealthStandard> findStandardByPatient(String patient) {
        return patientHealthStandardDao.findByPatient(patient);
    }
    /**
     * 保存患者健康指标预警值
     *
     * @param list
     */
    public Iterable<PatientHealthStandard> saveStandard(List<PatientHealthStandard> list, String patient) {
        // 先删除
        patientHealthStandardDao.deleteByPatient(patient);
        return patientHealthStandardDao.save(list);
    }
    /**
     * 查询患者最近填写的运动、用药、饮食内容
     *
     * @param patient
     * @return
     */
    public JSONArray findRecentByPatient(String patient) {
        JSONArray array = new JSONArray();
        Iterable<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
        if (iterable != null) {
            Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
            while (iterator != null && iterator.hasNext()) {
                DevicePatientHealthIndex phi = iterator.next();
                if (phi == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                // 设置健康指标类型(1血糖,2血压,3体重,4腰围)
                json.put("type", phi.getType());
                // 设置血糖/收缩压/体重/腰围/早餐前空腹
                json.put("value1", phi.getValue1());
                // 设置舒张压/早餐后血糖
                json.put("value2", phi.getValue2());
                // 设置午餐前血糖
                json.put("value3", phi.getValue3());
                // 设置午餐后血糖
                json.put("value4", phi.getValue4());
                // 设置晚餐前血糖
                json.put("value5", phi.getValue5());
                // 设置晚餐后血糖
                json.put("value6", phi.getValue6());
                // 设置睡前血糖
                json.put("value7", phi.getValue7());
                json.put("date", DateUtil.dateToStrShort(phi.getRecordDate()));
                array.put(json);
            }
        }
        return array;
    }
    /**
     * 查询上一次的值
     *
     * @param patient 患者标识
     * @param type    类型:1血糖,2血压
     * @param index   第几个值,1~7
     * @return
     */
    private String findPreValue(String patient, int type, int index, Date recordDate) {
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, 1);
        Page<String> page = null;
        switch (index) {
            case 1:
                page = patientHealthIndexDao.findValue1ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 2:
                page = patientHealthIndexDao.findValue2ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 3:
                page = patientHealthIndexDao.findValue3ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 4:
                page = patientHealthIndexDao.findValue4ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 5:
                page = patientHealthIndexDao.findValue5ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 6:
                page = patientHealthIndexDao.findValue6ByPatient(patient, type, recordDate, pageRequest);
                break;
            case 7:
                page = patientHealthIndexDao.findValue7ByPatient(patient, type, recordDate, pageRequest);
                break;
        }
        if (page != null && page.getNumberOfElements() > 0) {
            return page.getContent().get(0);
        }
        return "0";
    }
    /**
     * 根据患者标志获取健康指标
     *
     * @param patientCode 患者标志
     * @return 健康指标列表
     */
    public DevicePatientHealthIndex findLastByPatien(String patientCode, int type) {
        //最新血糖指标
        if (type == 1) {
            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, 1);
            if (obj != null) {
                String dateString = DateUtil.dateToStrShort(obj.getRecordDate());
                return getPatientXT(patientCode, dateString);
            } else {
                return null;
            }
        } else {  //其他指标
            return patientHealthIndexDao.findLastData(patientCode, 2);
        }
    }
}

+ 42 - 23
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java

@ -86,22 +86,22 @@ public class SignPatientLabelInfoService extends BaseService {
                    " where " + (doc.getLevel() == 2 ? " doctor" : "doctor_health") + " = ? and status > 0 and admin_team_code = ? ";
            if (labelCode.equals("1")) {
                int week = today.get(Calendar.DAY_OF_WEEK) - 1;
                int week = today.get(Calendar.DAY_OF_WEEK) - 2;
                if (week == 0) {
                if (week == -1) {
                    week = 6;
                }
                startDate.add(Calendar.DATE, -week);
                sql += " and apply_date >= '" + (df.format(startDate.getTime()) + " 00:00:00")
                        + "' and apply_date <= '" + (df.format(today.getTime()) + " 23:59:59'");
                sql += " and apply_date between '" + (df.format(startDate.getTime()) + " 00:00:00")
                        + "' and '" + (df.format(today.getTime()) + " 23:59:59'");
            } else if (labelCode.equals("2")) {
                startDate.set(Calendar.DATE, 1);
                sql += " and apply_date >= '" + (df.format(startDate.getTime()) + " 00:00:00")
                        + "' and apply_date <= '" + (df.format(today.getTime()) + " 23:59:59'");
                sql += " and apply_date between '" + (df.format(startDate.getTime()) + " 00:00:00")
                        + "' and '" + (df.format(today.getTime()) + " 23:59:59'");
            } else if (labelCode.equals("3")) {
                startDate.add(Calendar.DATE, 29);
                sql += " and apply_date >= '" + (df.format(today.getTime()) + " 00:00:00")
                        + "' and apply_date <= '" + (df.format(startDate.getTime()) + " 23:59:59'");
                startDate.add(Calendar.DATE, 30);
                sql += " and end between '" + (df.format(today.getTime()) + " 00:00:00")
                        + "' and '" + (df.format(startDate.getTime()) + " 23:59:59'");
            } else {
                throw new Exception("label is not exist");
            }
@ -114,7 +114,9 @@ public class SignPatientLabelInfoService extends BaseService {
                        " FROM " +
                        "    wlyy_sign_family t1 " +
                        " left join " +
                        "    (select patient,label,label_type from wlyy_sign_patient_label_info where label_type = ? and status = 1) t2 " +
                        "    (select patient,label,label_type from wlyy_sign_patient_label_info where patient in " +
                        "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + "='" + doctor + "' and status > 0) " +
                        "     and label_type = ? and status = 1) t2 " +
                        " on t1.patient = t2.patient " +
                        " WHERE " +
                        "    t2.patient is null " +
@ -130,7 +132,8 @@ public class SignPatientLabelInfoService extends BaseService {
                        "    wlyy_sign_family t1, " +
                        "    wlyy_sign_patient_label_info t2 " +
                        " WHERE " +
                        "    t2.label = ? " +
                        "     t2.patient in (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0 ) " +
                        "    AND t2.label = ? " +
                        "    AND t2.label_type = ? " +
                        "    AND t2.status = 1 " +
                        "    AND t1.patient = t2.patient " +
@ -158,6 +161,9 @@ public class SignPatientLabelInfoService extends BaseService {
                    if (!String.valueOf(jsonP.get("signType")).equals(String.valueOf(sign.get("type")))) {
                        jsonP.put("signType", 3);
                    }
                    if (String.valueOf(sign.get("type")).equals("2")) {
                        jsonP.put("qyrq", sign.get("apply_date") != null ? DateUtil.dateToStr((Date) sign.get("apply_date"), DateUtil.YYYY_MM_DD) : "");
                    }
                    continue;
                }
@ -181,6 +187,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("signType", sign.get("type") == null ? "" : sign.get("type"));
                // 身份证号
                json.put("idcard", p.getIdcard());
                // 社保号
                json.put("ssc", p.getSsc());
                // 患者标签
                //json.put("labels", labels == null ? "" : labels);
@ -274,6 +282,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("signType", sign.get("type") == null ? "" : sign.get("type"));
                // 身份证号
                json.put("idcard", p.getIdcard());
                // 社保号
                json.put("ssc", p.getSsc());
                // 患者标签
                json.put("labels", labels == null ? "" : labels);
@ -342,16 +352,16 @@ public class SignPatientLabelInfoService extends BaseService {
                            week = 6;
                        }
                        startDate.add(Calendar.DATE, -week);
                        sql += " and apply_date >= '" + (df.format(startDate.getTime()) + " 00:00:00")
                                + "' and apply_date <= '" + (df.format(today.getTime()) + " 23:59:59'");
                        sql += " and apply_date between '" + (df.format(startDate.getTime()) + " 00:00:00")
                                + "' and '" + (df.format(today.getTime()) + " 23:59:59'");
                    } else if (label.getLabelCode().equals("2")) {
                        startDate.set(Calendar.DATE, 1);
                        sql += " and apply_date >= '" + (df.format(startDate.getTime()) + " 00:00:00")
                                + "' and apply_date <= '" + (df.format(today.getTime()) + " 23:59:59'");
                        sql += " and apply_date between '" + (df.format(startDate.getTime()) + " 00:00:00")
                                + "' and '" + (df.format(today.getTime()) + " 23:59:59'");
                    } else if (label.getLabelCode().equals("3")) {
                        startDate.add(Calendar.DATE, 29);
                        sql += " and apply_date >= '" + (df.format(today.getTime()) + " 00:00:00")
                                + "' and apply_date <= '" + (df.format(startDate.getTime()) + " 23:59:59'");
                        startDate.add(Calendar.DATE, 30);
                        sql += " and end between '" + (df.format(today.getTime()) + " 00:00:00")
                                + "' and '" + (df.format(startDate.getTime()) + " 23:59:59'");
                    } else {
                        throw new Exception("label is not exist");
                    }
@ -367,7 +377,9 @@ public class SignPatientLabelInfoService extends BaseService {
                                " FROM" +
                                "     wlyy_sign_family t1 " +
                                " left join " +
                                "    (SELECT patient,label,label_type from wlyy_sign_patient_label_info where label_type = ? and status = 1)  t2 " +
                                "    (SELECT patient,label,label_type from wlyy_sign_patient_label_info where patient in " +
                                "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                                "    and label_type = ? and status = 1)  t2 " +
                                " on t1.patient = t2.patient " +
                                " WHERE" +
                                "     t2.patient is null " +
@ -388,6 +400,7 @@ public class SignPatientLabelInfoService extends BaseService {
                                "     wlyy_sign_patient_label_info t2 " +
                                " WHERE" +
                                "     t1.patient = t2.patient " +
                                "     AND t2.patient in (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                                "     AND t2.label = ? " +
                                "     AND t2.label_type = ? " +
                                "     AND t2.status = 1 " +
@ -627,17 +640,18 @@ public class SignPatientLabelInfoService extends BaseService {
                "    wlyy_sign_family t1 " +
                (StringUtils.isNotEmpty(labelCode) || StringUtils.isNotEmpty(labelType) ?
                        " join " : " left join ") +
                "    (select patient,label,label_name,label_type from wlyy_sign_patient_label_info " +
                "    where status = 1 " +
                "    (select patient,label,label_name,label_type from wlyy_sign_patient_label_info  where patient in" +
                "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                "     and status = 1 " +
                (StringUtils.isNotEmpty(labelCode) ? " AND label = ? " : "") +
                (StringUtils.isNotEmpty(labelType) ? " AND label_type = ? " : "") + ") t2" +
                " ON t1.patient = t2.patient " +
                " WHERE " +
                "    t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                "    AND t1.status > 0 " +
                (teamCode > 0 ? (" AND admin_team_code = " + teamCode) : "") +
                "    AND (t1.name like ? OR t2.label_name like ?) " +
                (teamCode > 0 ? (" AND admin_team_code = " + teamCode) : "")
                + " limit " + page + "," + pagesize;
                " limit " + page + "," + pagesize;
        if (StringUtils.isNotEmpty(labelCode)) {
            args = new Object[]{labelCode, labelType, doctor, "%" + filter + "%", "%" + filter + "%"};
@ -663,6 +677,9 @@ public class SignPatientLabelInfoService extends BaseService {
                    if (!String.valueOf(jsonP.get("signType")).equals(String.valueOf(sign.get("type")))) {
                        jsonP.put("signType", 3);
                    }
                    if (String.valueOf(sign.get("type")).equals("2")) {
                        jsonP.put("qyrq", sign.get("apply_date") != null ? DateUtil.dateToStr((Date) sign.get("apply_date"), DateUtil.YYYY_MM_DD) : "");
                    }
                    continue;
                }
@ -706,6 +723,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("signType", sign.get("type") == null ? "" : sign.get("type"));
                // 身份证号
                json.put("idcard", p.getIdcard());
                // 社保号
                json.put("ssc", p.getSsc());
                // 患者标签
                json.put("labels", labels == null ? "" : labels);

+ 97 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/DrugService.java

@ -0,0 +1,97 @@
package com.yihu.wlyy.service.app.record;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by zhenglingfeng on 2016/10/17.
 */
@Service
public class DrugService extends BaseService {
    @Autowired
    SystemDictService systemDictService;
    /**
     * 获取用药记录
     */
    public String getDrugsList(String strSSID, String startNum,String endNum) throws Exception {
        String startDate = "1900-01-01";
        String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/third/smjk/DrugsList";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSSID", strSSID));
        params.add(new BasicNameValuePair("startDate", startDate));
        params.add(new BasicNameValuePair("endDate", endDate));
        params.add(new BasicNameValuePair("startNum", startNum));
        params.add(new BasicNameValuePair("endNum", endNum));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        JSONArray resultArray = new JSONArray();
        List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
        Map<String, String> systemDictMap = new HashMap<>();
        for (SystemDict systemDict : systemDictList) {
            systemDictMap.put(systemDict.getCode(), systemDict.getValue());
        }
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200){
                String data = responseObject.getString("data");
                if (!StringUtils.isEmpty(data)){
                    if (data.startsWith("error")) {
                        return data;
                    }
                    JSONObject jsonData = new JSONObject(data);
                    JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                    if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                        for (int i=0; i<jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String patientId = jsonObject.getString("XMAN_ID");
                            String eventNo = jsonObject.getString("EVENT");
                            Integer orgId = jsonObject.getInt("ORG_ID");
                            String key = patientId + eventNo + orgId;
                            JSONObject catalogObject = new JSONObject();
                            String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                            String catalogValue = systemDictMap.get(catalogCode);
                            jsonObject.remove("CATALOG_CODE");
                            if (jsonObjectMap.containsKey(key)) {
                                jsonObject = jsonObjectMap.get(key);
                                catalogObject = jsonObject.getJSONObject("CATALOG");
                            }
                            catalogObject.put(catalogCode, catalogValue);
                            jsonObject.put("CATALOG", catalogObject);
                            jsonObjectMap.put(key, jsonObject);
                        }
                        for (String key : jsonObjectMap.keySet()) {
                            resultArray.put(jsonObjectMap.get(key));
                        }
                    }
                }
            }
        }
        return resultArray.toString();
    }
}

+ 59 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/HealthDataService.java

@ -0,0 +1,59 @@
package com.yihu.wlyy.service.app.record;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by zhenglingfeng on 2016/10/17.
 */
@Service
public class HealthDataService extends BaseService {
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 获取健康档案信息
     */
    public String getHealthData(String strSSID, String strEvent, String strCatalog, String strSerial) throws Exception {
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/third/smjk/HealthData";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSSID", strSSID));
        params.add(new BasicNameValuePair("strEvent", strEvent));
        params.add(new BasicNameValuePair("strCatalog", strCatalog));
        params.add(new BasicNameValuePair("strSerial", strSerial));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        String result = "";
        if (!StringUtils.isEmpty(response)){
            JSONObject jsonObject = new JSONObject(response);
            int status = jsonObject.getInt("status");
            if (status == 200){
                result = jsonObject.getString("data");
                result = result.replaceAll("<\\?xml version=\"1.0\" encoding=\"utf-8\"\\?>","");
                if (result.startsWith("error")) {
                    return result;
                }
//                if (!StringUtils.isEmpty(xmlData)){
//                    String xmlJson = XMLUtil.xml2json(xmlData);
//                    result = objectMapper.readValue(xmlJson, Map.class);
//                }
            }
        }
        return result;
    }
}

+ 94 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/HospitalizationService.java

@ -0,0 +1,94 @@
package com.yihu.wlyy.service.app.record;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by zhenglingfeng on 2016/10/17.
 */
@Service
public class HospitalizationService extends BaseService {
    @Autowired
    SystemDictService systemDictService;
    /**
     * 获取住院记录
     */
    public String getHospitalizationRecord(String strSSID, String startNum, String endNum) throws Exception {
        String startDate = "1900-01-01";
        String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/third/smjk/InpatientRecord";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSSID", strSSID));
        params.add(new BasicNameValuePair("startDate", startDate));
        params.add(new BasicNameValuePair("endDate", endDate));
        params.add(new BasicNameValuePair("startNum", startNum));
        params.add(new BasicNameValuePair("endNum", endNum));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        JSONArray resultArray = new JSONArray();
        List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
        Map<String, String> systemDictMap = new HashMap<>();
        for (SystemDict systemDict : systemDictList) {
            systemDictMap.put(systemDict.getCode(), systemDict.getValue());
        }
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200){
                String data = responseObject.getString("data");
                if (!StringUtils.isEmpty(data)){
                    JSONObject jsonData = new JSONObject(data);
                    JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                    if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                        for (int i=0; i<jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String patientId = jsonObject.getString("XMAN_ID");
                            String eventNo = jsonObject.getString("EVENT");
                            Integer orgId = jsonObject.getInt("ORG_ID");
                            String key = patientId + eventNo + orgId;
                            JSONObject catalogObject = new JSONObject();
                            String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                            String catalogValue = systemDictMap.get(catalogCode);
                            jsonObject.remove("CATALOG_CODE");
                            if (jsonObjectMap.containsKey(key)) {
                                jsonObject = jsonObjectMap.get(key);
                                catalogObject = jsonObject.getJSONObject("CATALOG");
                            }
                            catalogObject.put(catalogCode, catalogValue);
                            jsonObject.put("CATALOG", catalogObject);
                            jsonObjectMap.put(key, jsonObject);
                        }
                        for (String key : jsonObjectMap.keySet()) {
                            resultArray.put(jsonObjectMap.get(key));
                        }
                    }
                }
            }
        }
        return resultArray.toString();
    }
}

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 220 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/InspectionService.java


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 224 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/OutpatientService.java


+ 94 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/RegDeptSpeDoctorService.java

@ -0,0 +1,94 @@
package com.yihu.wlyy.service.app.record;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by zhenglingfeng on 2016/10/17.
 */
@Service
public class RegDeptSpeDoctorService extends BaseService {
    @Autowired
    SystemDictService systemDictService;
    /**
     * 获取转诊预约医生号源信息
     */
    public String getRegDeptSpeDoctorSectionList(String OrgCode,String DeptCode,String strStart,String strEnd,String DocCode)  throws Exception
    {
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/third/smjk/RegDeptSpeDoctorSectionList";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("OrgCode", OrgCode));
        params.add(new BasicNameValuePair("DeptCode", DeptCode));
        params.add(new BasicNameValuePair("strStart", strStart));
        params.add(new BasicNameValuePair("strEnd", strEnd));
        params.add(new BasicNameValuePair("DocCode", DocCode));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        JSONArray resultArray = new JSONArray();
        List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
        Map<String, String> systemDictMap = new HashMap<>();
        for (SystemDict systemDict : systemDictList) {
            systemDictMap.put(systemDict.getCode(), systemDict.getValue());
        }
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200){
                String data = responseObject.getString("data");
                if (!StringUtils.isEmpty(data)){
                    if (data.startsWith("error")) {
                        return data;
                    }
                    JSONObject jsonData = new JSONObject(data);
                    JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                    if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                        for (int i=0; i<jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String patientId = jsonObject.getString("XMAN_ID");
                            String eventNo = jsonObject.getString("EVENT");
                            Integer orgId = jsonObject.getInt("ORG_ID");
                            String key = patientId + eventNo + orgId;
                            JSONObject catalogObject = new JSONObject();
                            String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                            String catalogValue = systemDictMap.get(catalogCode);
                            jsonObject.remove("CATALOG_CODE");
                            if (jsonObjectMap.containsKey(key)) {
                                jsonObject = jsonObjectMap.get(key);
                                catalogObject = jsonObject.getJSONObject("CATALOG");
                            }
                            catalogObject.put(catalogCode, catalogValue);
                            jsonObject.put("CATALOG", catalogObject);
                            jsonObjectMap.put(key, jsonObject);
                        }
                        for (String key : jsonObjectMap.keySet()) {
                            resultArray.put(jsonObjectMap.get(key));
                        }
                    }
                }
            }
        }
        return resultArray.toString();
    }
}

+ 8 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java

@ -57,7 +57,14 @@ public class DoctorWorkTimeService extends BaseService {
        result.put("workTime", workTime != null ? new JSONObject(workTime) : "");
        result.put("workWeeks", workWeekList != null ? new JSONArray(workWeekList) : "");
        result.put("doctor", doc != null ? new JSONObject(doc) : "");
        JSONObject docJson = new JSONObject(doc);
        if(docJson.has("password")) {
            docJson.remove("password");
        }
        if(docJson.has("salt")) {
            docJson.remove("salt");
        }
        result.put("doctor", doc != null ? docJson : "");
        return result;
    }

+ 23 - 4
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java

@ -27,6 +27,7 @@ import com.yihu.wlyy.repository.statistics.WlyySignFamilyCodeDao;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.task.SignUploadTask;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@ -640,7 +641,8 @@ public class FamilyContractService extends BaseService {
                                         String majorDoctor,
                                         String majorDoctorName,
                                         String hospital, String hospitalName,
                                         String idcard, String ssc, String mobile,
                                         String idcard, String ssc,
                                         String mobile,
                                         String emerMobile, String images,
                                         String healthLabel, String customLabel, String disease,
                                         String expenses, String signDoctorCode,
@ -712,9 +714,13 @@ public class FamilyContractService extends BaseService {
            patient.setName(name);
            patient.setIdcard(idcard);
            patient.setSsc(sscD);
            patient.setMobile(mobile);
            patient.setBirthday(ie.getBirthday());
            patient.setSex(ie.getGender());
            patient.setMobile(mobile);
            String password=idcard.substring(idcard.length()-6);
            String salt= UUID.randomUUID().toString().replace("-","");
            patient.setSalt(salt);
            patient.setPassword(MD5.GetMD5Code(password+salt));
            patient.setStatus(1);
            patient.setDisease(0);
        }
@ -1317,7 +1323,6 @@ public class FamilyContractService extends BaseService {
                result.put("diseases", "");
            }
            result.put("signStatus", "1");
        } else {
@ -1326,6 +1331,12 @@ public class FamilyContractService extends BaseService {
        if (p != null) {
            JSONObject pJson = new JSONObject(p);
            if (pJson.has("password")) {
                pJson.remove("password");
            }
            if (pJson.has("salt")) {
                pJson.remove("salt");
            }
            result.put("patient", pJson);
        }
@ -1427,7 +1438,6 @@ public class FamilyContractService extends BaseService {
        return true;
    }
    public String produceSignAdminTeamCode() {
        StringBuffer sf = new StringBuffer();
        StringBuffer sf1 = new StringBuffer();
@ -1535,4 +1545,13 @@ public class FamilyContractService extends BaseService {
        return signFamilyDao.findNoHealthSignFamilyHealth(doctor, pageRequest);
    }
    /**
     * 查询居民的所有签约
     *
     * @param patient
     * @return
     */
    public List<SignFamily> findAllSignByPatient(String patient) {
        return signFamilyDao.findAllSignByPatient(patient);
    }
}

+ 0 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsAllService.java


Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio