LAPTOP-KB9HII50\70708 2 år sedan
förälder
incheckning
e1d59072f4
49 ändrade filer med 9993 tillägg och 257 borttagningar
  1. 19 0
      svr/svr-basic/pom.xml
  2. 447 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/common/SystemDictController.java
  3. 177 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/QuotaCategoryController.java
  4. 191 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDataSaveController.java
  5. 238 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDataSourceController.java
  6. 259 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDimensionMainController.java
  7. 258 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDimensionSlaveController.java
  8. 947 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaController.java
  9. 67 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaDimensionMainController.java
  10. 67 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaDimensionSlaveController.java
  11. 664 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/report/ReportController.java
  12. 127 171
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceBrowseController.java
  13. 4 1
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceDefaultParamController.java
  14. 9 12
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceInterfaceController.java
  15. 4 2
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/RsResourceCategoryController.java
  16. 26 20
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/service/ResourceBrowseControllerService.java
  17. 3 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/config/Config.java
  18. 0 26
      svr/svr-basic/src/main/java/com/yihu/jw/basic/config/TenantConfiguration.java
  19. 446 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/es/EsResultExtract.java
  20. 45 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticSearchConfig.java
  21. 80 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticSearchPool.java
  22. 402 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticsearchUtil.java
  23. 58 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/EsClientUtil.java
  24. 926 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/QuotaReportController.java
  25. 1 2
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjDataSaveEndPoint.java
  26. 2 5
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjDimensionMainEndPoint.java
  27. 1 1
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjQuotaCategoryEndPoint.java
  28. 18 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/dao/TjQuotaGovProvisionDao.java
  29. 387 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/model/SaveModel.java
  30. 2001 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/BaseStatistsService.java
  31. 63 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/DeviceService.java
  32. 265 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/OrgHealthCategoryStatisticsService.java
  33. 292 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/QuotaService.java
  34. 901 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/SingleDiseaseService.java
  35. 12 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDataSaveService.java
  36. 21 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDataSourceService.java
  37. 11 2
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDimensionMainService.java
  38. 16 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDimensionSlaveService.java
  39. 0 2
      svr/svr-basic/src/main/java/com/yihu/jw/basic/report/controller/QcQuotaResultEndPoint.java
  40. 19 6
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/controller/RsResourceGrantEndPoint.java
  41. 1 5
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/RsResourceDefaultParamDao.java
  42. 7 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/RsResourceQuotaDao.java
  43. 4 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsInterfaceService.java
  44. 1 1
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsResourceDefaultParamService.java
  45. 15 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsResourceQuotaService.java
  46. 72 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/util/BasesicUtil.java
  47. 387 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/util/ReportOption.java
  48. 29 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/util/model/ChartDataModel.java
  49. 3 1
      svr/svr-basic/src/main/resources/application.yml

+ 19 - 0
svr/svr-basic/pom.xml

@ -28,6 +28,25 @@
                </exclusion>
            </exclusions>
        </dependency>
        <!-- es -->
        <!-- ElasticSearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.1.0</version>
        </dependency>
        <!-- ElasticSearch -->
        <dependency>
            <groupId>com.github.abel533</groupId>
            <artifactId>ECharts</artifactId>
            <version>2.2.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>

+ 447 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/common/SystemDictController.java

@ -0,0 +1,447 @@
package com.yihu.jw.basic.agadmin.controller.common;
import com.yihu.jw.basic.dict.service.SystemDictEntryService;
import com.yihu.jw.basic.dict.service.SystemDictService;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2015/8/12.
 */
@RequestMapping("/dict")
@RestController
@Api( tags = {"网关-字典"})
public class SystemDictController extends EnvelopRestEndpoint {
    @Autowired
    private SystemDictService dictService;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
//
//    @RequestMapping("/createDict")
//    public Envelop createDict(String name, String reference, String userId) {
//        Map<String, Object> params = new HashMap<>();
//        if (StringUtils.isEmpty(name)){
//            return failed("字典名称不能为空");
//        }
//        SystemDictModel systemDictModel = new SystemDictModel();
//        systemDictModel.setName(name.replace(" ", ""));
//        systemDictModel.setAuthorId("System");
//        params.put("dictionary", toJson(systemDictModel));
//        try {
//            String urlCheck = "/basic/api/v1.0/dictionaries/existence";
//            Map<String, Object> paramsCheck = new HashMap<>();
//            paramsCheck.put("dict_name",name);
//            String resultCheckStr = HttpClientUtil.doGet(adminInnerUrl + urlCheck, paramsCheck, username, password);
//            boolean exists = Boolean.valueOf(resultCheckStr);
//            if (exists) {
//                return failed("字典名字在系统中已存在");
//            }
//            String url = "/basic/api/v1.0/dictionaries";
//            HttpResponse resultStr = HttpUtils.doJsonPost(adminInnerUrl + url, toJson(systemDictModel), null, username, password);
//            if (resultStr.isSuccessFlg()) {
//                return toModel(resultStr.getContent(), Envelop.class);
//            } else {
//                return failed(resultStr.getContent());
//            }
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ex.getMessage());
//        }
//    }
//
//    @RequestMapping("/deleteDict")
//    public Envelop deleteDict(long dictId) {
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("dictId", dictId);
//            String url ="/basic/api/v1.0/dictionaries/" + dictId;
//            String resultStr = HttpClientUtil.doDelete(adminInnerUrl + url, params, username, password);
//            boolean success = Boolean.valueOf(resultStr);
//            if (success) {
//                return success(true);
//            }
//            return failed("删除失败");
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ex.getMessage());
//        }
//    }
//
//    @RequestMapping("/updateDict")
//    public Envelop updateDict(long dictId, String name) {
//        if (StringUtils.isEmpty(name)) {
//            return failed("字典名称不能为空");
//        }
//        try {
//            Map<String, Object> dictParams = new HashMap<>();
//            dictParams.put("id", dictId);
//            dictParams.put("name", name.replace(" ", ""));
//            String url = "/basic/api/v1.0/dictionaries";
//            HttpResponse httpResponse = HttpUtils.doJsonPut(adminInnerUrl + url, toJson(dictParams), null, username, password);
//            if (httpResponse.isSuccessFlg()) {
//                return toModel(httpResponse.getContent(), Envelop.class);
//            } else {
//                return failed(httpResponse.getContent());
//            }
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ex.getMessage());
//        }
//    }
    @GetMapping("searchSysDicts")
    public Envelop searchSysDicts(String searchNm, Integer page, Integer rows) {
        String resultStr = "";
        Envelop result = new Envelop();
        Map<String, Object> params = new HashMap<>();
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(searchNm)) {
            stringBuffer.append("name?" + searchNm + " g1;phoneticCode?" + searchNm + " g1");
        }
        String filters = stringBuffer.toString();
        params.put("filters", "");
        if (!StringUtils.isEmpty(filters)) {
            params.put("filters", filters);
        }
        params.put("page", page);
        params.put("size", rows);
        try {
            if (page != null || page > 0) {
                page = page - 1;
            }else {
                page = 1;
            }
            String url ="/dictionaries";
            page = reducePage(page);
            if (org.apache.commons.lang3.StringUtils.isEmpty(filters)) {
                Page<SystemDict> systemDictPage = dictService.getDictList(null, page, rows);
                return PageEnvelop.getSuccessListWithPage("",systemDictPage.toList(),page,rows,systemDictPage.getTotalElements());
            } else {
                List<SystemDict> systemDictList = dictService.search(null, filters, null, page, rows);
                return PageEnvelop.getSuccessListWithPage("",systemDictList,page,rows, dictService.getCount(filters));
            }
        } catch (Exception ex){
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
//    @RequestMapping("createDictEntry")
//    public Object createDictEntry(Long dictId, String code, String value, Integer sort, String catalog) {
//
//        Map<String, Object> params = new HashMap<>();
//        Envelop result = new Envelop();
//        String resultStr = "";
//
//        if(StringUtils.isEmpty(dictId)){
//            result.setSuccessFlg(false);
//            result.setErrorMsg("字典Id不能为空!");
//            return result;
//        }
//        if(StringUtils.isEmpty(code)){
//            result.setSuccessFlg(false);
//            result.setErrorMsg("字典项编码不能为空!");
//            return result;
//        }
//        if(StringUtils.isEmpty(value)){
//            result.setSuccessFlg(false);
//            result.setErrorMsg("字典项值不能为空!");
//            return result;
//        }
//
//        SystemDictEntryModel dictEntryModel = new SystemDictEntryModel();
//        dictEntryModel.setDictId(dictId);
//        dictEntryModel.setCode(code.replace(" ", ""));
//        dictEntryModel.setValue(value.replace(" ", ""));
//        dictEntryModel.setSort(sort);
//        dictEntryModel.setCatalog(catalog);
//        params.put("entry",toJson(dictEntryModel));
//
//        try {
//            String urlCheck = "/dictionaries/existence/" + dictId ;
//            Map<String, Object> paramsCheck = new HashMap<>();
//            paramsCheck.put("dict_id",dictId);
//            paramsCheck.put("code",code.replace(" ", ""));
//            String resultCheckStr = HttpClientUtil.doGet(comUrl + urlCheck, paramsCheck, username, password);
//
//            if(Boolean.parseBoolean(resultCheckStr)){
//                result.setSuccessFlg(false);
//                result.setErrorMsg("代码在该字典中已存在,请确认。");
//                return result;
//            }
//
//            String url = "/dictionaries/entries";
//            resultStr = HttpClientUtil.doPost(comUrl+url,params,username,password);
//            return resultStr;
//
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    @RequestMapping("deleteDictEntry")
//    @ResponseBody
//    public Object deleteDictEntry(long dictId, String code) throws Exception{
//
//        Envelop result = new Envelop();
//        String resultStr = "";
//        Map<String, Object> params = new HashMap<>();
//        params.put("id",dictId);
//        params.put("code",code);
//
//        String url = "/dictionaries/"+ dictId + "/entries/"+ URLEncoder.encode(code, "UTF-8");
//
//        try {
//            resultStr = HttpClientUtil.doDelete(comUrl+url,params,username,password);
//            return resultStr;
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    @RequestMapping("updateDictEntry")
//    @ResponseBody
//    public Object updateDictEntry(Long dictId, String code, String value, Integer sort, String catalog) {
//
//        Map<String, Object> params = new HashMap<>();
//        Envelop result = new Envelop();
//        String resultStr = "";
//
//        if(StringUtils.isEmpty(dictId)){
//            result.setSuccessFlg(false);
//            result.setErrorMsg("字典id不能为空!");
//            return result;
//        }
//        if(StringUtils.isEmpty(code)){
//            result.setSuccessFlg(false);
//            result.setErrorMsg("字典项编码code不能为空!");
//            return result;
//        }
//
//        SystemDictEntryModel dictEntryModel = new SystemDictEntryModel();
//        dictEntryModel.setDictId(dictId);
//        dictEntryModel.setCode(code.replace(" ", ""));
//        dictEntryModel.setValue(value.replace(" ", ""));
//        dictEntryModel.setSort(sort);
//        dictEntryModel.setCatalog(catalog);
//        params.put("dictionary",toJson(dictEntryModel));
//
//        try {
//            String dictEntryUrl = "/dictionaries/" + dictId + "/entries/" + URLEncoder.encode(code,"UTF-8");
//            Map<String, Object> dictEntryParams = new HashMap<>();
//            dictEntryParams.put("dict_id",dictId);
//            dictEntryParams.put("code",code);
//            String dictEntryResultStr = HttpClientUtil.doGet(comUrl + dictEntryUrl, dictEntryParams, username, password);
//            result = getEnvelop(dictEntryResultStr);
//
//            if(result.isSuccessFlg()){
//                SystemDictEntryModel systemDictEntryModel = getEnvelopModel(result.getObj(),SystemDictEntryModel.class);
//                systemDictEntryModel.setValue(value.replace(" ", ""));
//                systemDictEntryModel.setSort(sort);
//                systemDictEntryModel.setCatalog(catalog);
//                params.put("entry",toJson(systemDictEntryModel));
//
//                String urlCheckDict = "/dictionaries/entries";
//                resultStr = HttpClientUtil.doPut(comUrl + urlCheckDict, params, username, password);
//                return resultStr;
//            }
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return result;
//    }
//
//    @RequestMapping("searchDictEntryListForManage")
//    @ResponseBody
//    public Object searchDictEntryList(Long dictId, Integer page, Integer rows) {
//
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!StringUtils.isEmpty(dictId)) {
//            stringBuffer.append("dictId=" + dictId);
//        }
//        String filters = stringBuffer.toString();
//        params.put("filters", "");
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//
//        try {
//            String url ="/dictionaries/entries";
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    @RequestMapping("selecttags")
//    @ResponseBody
//    public Object selectTags() {
//
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//
//        try {
//            String url ="/dictionaries/tags";
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//
//            ObjectMapper objectMapper = new ObjectMapper();
//            result = objectMapper.readValue(resultStr, Envelop.class);
//            result.setObj(result.getDetailModelList());
//
//            return result;
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
    @GetMapping("searchDictEntryList")
    public Envelop searchDictEntryListForDDL(Long dictId, Integer page, Integer rows) {
        String resultStr = "";
        Envelop result = new Envelop();
        Map<String, Object> params = new HashMap<>();
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(dictId)) {
            stringBuffer.append("dictId=" + dictId);
        }
        String filters = stringBuffer.toString();
        params.put("filters", "");
        if (!StringUtils.isEmpty(filters)) {
            params.put("filters", filters);
        }
        if(StringUtils.isEmpty(page) || page == 0){
            page = 1;
        }
        if(StringUtils.isEmpty(rows) || rows == 0){
            rows = 50;
        }
        params.put("page", page);
        params.put("size", rows);
        try {
            String url ="/dictionaries/entries";
            List<SystemDictEntry> systemDictEntryList = systemDictEntryService.search(null,filters,null,page,rows);
            return PageEnvelop.getSuccessListWithPage("",systemDictEntryList,page,rows, systemDictEntryService.getCount(filters));
        }catch (Exception ex){
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
//    @RequestMapping("searchDictForSelect")
//    @ResponseBody
//    public Object searchDictForSelect(Long dictId, String searchParm, Integer page, Integer rows) {
//
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!StringUtils.isEmpty(dictId)) {
//            stringBuffer.append("dictId=" + dictId+";");
//        }
//        if (!StringUtils.isEmpty(searchParm)){
//            stringBuffer.append("code?"+searchParm+" g1;value?"+searchParm+" g1;");
//        }
//        String filters = stringBuffer.toString();
//        params.put("filters", "");
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        if(StringUtils.isEmpty(page) || page == 0){
//            page = 1;
//        }
//        if(StringUtils.isEmpty(rows) || rows == 0){
//            rows = 50;
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        params.put("sorts", "+sort");
//
//        try {
//            String url ="/dictionaries/entries";
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            Envelop envelopGet = objectMapper.readValue(resultStr,Envelop.class);
//            List<SystemDictEntryModel> modelList = (List<SystemDictEntryModel>)getEnvelopList(envelopGet.getDetailModelList(),new ArrayList<SystemDictEntryModel>(),SystemDictEntryModel.class);
//            List<Map> list = new ArrayList<>();
//            for (SystemDictEntryModel m:modelList){
//                Map map = new HashMap<>();
//                map.put("id", m.getCode());
//                map.put("name",m.getValue());
//                list.add(map);
//            }
//            envelopGet.setDetailModelList(list);
//            return envelopGet;
//        }catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    @RequestMapping("validator")
//    @ResponseBody
//    public Object validator(String systemName){
//        Envelop result = new Envelop();
//        String resultStr = "";
//
//        Map<String, Object> params = new HashMap<>();
//        params.put("dict_name",systemName);
//
//        try {
//            String url ="/dictionaries/existence";
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if(Boolean.parseBoolean(resultStr)){
//                result.setSuccessFlg(false);
//                result.setErrorMsg("名称重复");
//            }else{
//                result.setSuccessFlg(true);
//            }
//        } catch (Exception ex){
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return result;
//    }
//
//    @RequestMapping("autoSearchDictEntryList")
//    @ResponseBody
//    public Object autoSearchDictEntryList(Long dictId,String key){
//
//        return null  ;
//    }
}

+ 177 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/QuotaCategoryController.java

@ -0,0 +1,177 @@
package com.yihu.jw.basic.agadmin.controller.quota;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.jw.basic.quota.service.TjQuotaCategoryService;
import com.yihu.jw.basic.quota.service.TjQuotaService;
import com.yihu.jw.entity.ehr.quota.TjQuotaCategory;
import com.yihu.jw.restmodel.ehr.tj.MQuotaCategory;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by wxw on 2017/8/31.
 */
@RestController
@RequestMapping("/quota")
public class QuotaCategoryController extends EnvelopRestEndpoint {
    @Autowired
    private TjQuotaCategoryService quotaCategoryService;
    @Autowired
    private TjQuotaService tjQuotaService;
    @GetMapping("/getQuotaCategoryList")
    public Object getQuotaCategoryList(String name, String searchParm,Integer id, int page, int rows){
        String url = "/quotaCategory/pageList";
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(name)) {
            stringBuffer.append("name?" + name + " g1;code?" + name + " g1;");
        }
        if (!StringUtils.isEmpty(searchParm)) {
            stringBuffer.append("name?" + searchParm + ";");
        }
        if (!StringUtils.isEmpty(id)) {
            stringBuffer.append("id<>" + id + ";");
        }
        String filters = stringBuffer.toString();
        try {
            PageEnvelop pageEnvelop = new PageEnvelop();
            List<TjQuotaCategory> quotaCategoryList = quotaCategoryService.search(null, filters, null, page, rows);
            if (quotaCategoryList != null){
                pageEnvelop.setDetailModelList(quotaCategoryList);
                pageEnvelop.setTotalCount((int)quotaCategoryService.getCount(filters));
                pageEnvelop.setStatus(200);
                pageEnvelop.setCurrPage(page);
                pageEnvelop.setPageSize(rows);
            } else{
                pageEnvelop.setStatus(200);
                pageEnvelop.setMessage("查询无数据");
                pageEnvelop.setTotalCount(0);
            }
            return pageEnvelop;
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    @RequestMapping("deleteQuotaCategory")
    public Object deleteQuotaCategory(Integer id) {
        String url = "/basic/api/v1.0/quotaCategory/delete";
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        try {
            TjQuotaCategory tjQuotaCategory = quotaCategoryService.getById(id);
            if (null == tjQuotaCategory) {
                return failed( "操作对象不存在", ErrorCode.OBJECT_NOT_FOUND.value());
            }
            if (quotaCategoryService.findByField("parentId", id).size() > 0) {
                return failed("含有子分类,不能删除");
            }
            if (tjQuotaService.findByField("quotaType", id).size() > 0) {
                return failed("含有子类,不能删除");
            }
            quotaCategoryService.deleteQuotaCategory(id);
            return success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @GetMapping("detailById")
    public Envelop getTjQuotaById(Integer id ) {
        String url ="/quotaCategory/detailById";
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        MQuotaCategory detailModel = null;
        try {
            TjQuotaCategory quotaCategory = quotaCategoryService.getById(id);
            return ObjEnvelop.getSuccess("查询成功",quotaCategory);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
    @RequestMapping("/addOrUpdateQuotaCategory")
    public Envelop addOrUpdateQuotaCategory(String mode, String jsonDate){
        try{
            TjQuotaCategory quotaCategory = toEntity(jsonDate, TjQuotaCategory.class);
            if("new".equals(mode)){
                if (quotaCategoryService.getCountByName(quotaCategory.getName())>0){
                    return failed("名称不唯一");
                }
                if (quotaCategoryService.getCountByCode(quotaCategory.getCode())>0){
                    return failed("编码不唯一");
                }
                quotaCategory = quotaCategoryService.saveQuotaCategory(quotaCategory);
                return ObjEnvelop.getSuccess("保存成功",quotaCategory);
            } else if("modify".equals(mode)){
                quotaCategory = quotaCategoryService.updateQuotaCategory(quotaCategory);
                return ObjEnvelop.getSuccess("保存成功",quotaCategory);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
        return failed("查询失败");
    }
    @GetMapping("hasExistsName")
    public Envelop hasExistsName(String name) {
        try {
            return ObjEnvelop.getSuccess("查询成功",quotaCategoryService.getCountByName(name)>0);
        } catch (Exception e) {
            e.getMessage();
        }
        return failed("查询失败");
    }
    @GetMapping("hasExistsCode")
    public Envelop hasExistsCode(String code) {
        try {
            return ObjEnvelop.getSuccess("查询成功",quotaCategoryService.getCountByCode(code)>0);
        } catch (Exception e) {
            e.getMessage();
        }
        return failed("查询失败");
    }
    @GetMapping("/getAllQuotaCategoryList")
    public Object getAllQuotaCategoryList(){
        String url = "/quotaCategory/getQuotaCategoryChild";
        try {
            List<TjQuotaCategory> quotaCategories = quotaCategoryService.getQuotaCategoryChild();
            return ListEnvelop.getSuccess("查询成功",quotaCategories);
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    @GetMapping("/getQuotaCategoryListTree")
    public Object getQuotaCategoryListTree(){
        String url = "/quotaCategory/list";
        try {
            List<TjQuotaCategory> quotaCategories = quotaCategoryService.getAllQuotaCategory();
            return ListEnvelop.getSuccess("查询成功",quotaCategories);
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
}

+ 191 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDataSaveController.java

@ -0,0 +1,191 @@
package com.yihu.jw.basic.agadmin.controller.quota;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.quota.service.TjDataSaveService;
import com.yihu.jw.entity.ehr.quota.TjDataSave;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by llh on 2017/5/9.
 */
@RestController
@RequestMapping("/tjDataSave")
public class TjDataSaveController extends EnvelopRestEndpoint {
    @Autowired
    TjDataSaveService tjDataSaveService;
    //查询统计主维度
    @GetMapping("/getTjDataSave")
    public Envelop searchTjDataSave(String name, String searchParm,int page, int rows){
        String url = "/tj/getTjDataSaveList";
        String resultStr = "";
        Envelop envelop = new Envelop();
        Map<String, Object> params = new HashMap<>();
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(name)) {
            stringBuffer.append("name?" + name );
        }
        if (!StringUtils.isEmpty(searchParm)) {
            stringBuffer.append("name?" + searchParm );
        }
        String filters = stringBuffer.toString();
        try {
            PageEnvelop PageEnvelop = new PageEnvelop();
            List<TjDataSave> tjDataSaveList = tjDataSaveService.search(null, filters, null, page, rows);
            if(tjDataSaveList != null){
                PageEnvelop.setDetailModelList(tjDataSaveList);
                PageEnvelop.setTotalCount((int)tjDataSaveService.getCount(filters));
                PageEnvelop.setStatus(200);
                PageEnvelop.setCurrPage(page);
                PageEnvelop.setPageSize(rows);
            }else{
                PageEnvelop.setStatus(200);
                PageEnvelop.setMessage("查询无数据");
                PageEnvelop.setTotalCount(0);
            }
            return PageEnvelop;
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 新增修改
     * @param tjDataSaveModelJsonData
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "updateTjDataSave", produces = "text/html;charset=UTF-8")
    public Envelop updateTjDataSave(String tjDataSaveModelJsonData, HttpServletRequest request) throws IOException {
        String url = "/tj/addTjDataSave";
        String resultStr = "";
        System.out.println();
        Envelop result = new Envelop();
        String[] strings = URLDecoder.decode(tjDataSaveModelJsonData, "UTF-8").split(";");
        try {
            TjDataSave detailModel = objectMapper.readValue(strings[0], TjDataSave.class);
            if (!StringUtils.isEmpty(detailModel.getId())) {
                Long tjDataSaveId = detailModel.getId();
                TjDataSave updateTjDataSave = tjDataSaveService.getById(tjDataSaveId);
                if (updateTjDataSave !=null ) {
                    updateTjDataSave.setCode(detailModel.getCode());
                    updateTjDataSave.setName(detailModel.getName());
                    updateTjDataSave.setType(detailModel.getType());
                    updateTjDataSave.setStatus(detailModel.getStatus());
                    updateTjDataSave.setRemark(detailModel.getRemark());
                    updateTjDataSave.setUpdateTime(new Date());
                    tjDataSaveService.save(updateTjDataSave);
                    return ObjEnvelop.getSuccess("保存成功!", updateTjDataSave);
                } else {
                    return failed("参数错误");
                }
            } else {
                detailModel.setCreateTime(new Date());
                tjDataSaveService.save(detailModel);
                return ObjEnvelop.getSuccess("保存成功",detailModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 删除消息
     * @param tjDataSaveId
     * @return
     */
    @RequestMapping("deleteTjDataSave")
    public Envelop deleteTjDataSave(Long tjDataSaveId) {
        String url = "/tj/deleteTjDataSave";
        try {
            TjDataSave tjDataSave = tjDataSaveService.getById(tjDataSaveId);
            tjDataSave.setStatus(-1);
            tjDataSaveService.save(tjDataSave);
            return success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 根据id获取消息
     * @param id
     * @return
     */
    @GetMapping("getTjDataSaveById")
    public Envelop getTjQuotaById(Long id ) {
        String url ="/tj/getTjDataSaveById/" +id;
        try {
            TjDataSave updateTjDataSave = tjDataSaveService.getById(id);
            return ObjEnvelop.getSuccess("获取成功",updateTjDataSave);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return failed("查询失败");
    }
    /**
     * 校验name是否唯一,true已存在
     * @param name
     * @return
     */
    @GetMapping("hasExistsName")
    public Envelop hasExistsName(String name) {
        String url = "/tj/dataSaveExistsName/"+ name ;
        try {
            String filter = "name=" + name;
            List<TjDataSave> list = tjDataSaveService.search(filter);
            return ObjEnvelop.getSuccess("查询成功",list.size() > 0);
        } catch (Exception e) {
            e.getMessage();
        }
        return  failed("查询失败");
    }
    /**
     * 校验code是否唯一
     * @param code
     * @return
     */
    @GetMapping("hasExistsCode")
    public Envelop hasExistsCode(String code) {
        String url = "/tj/dataSaveExistsCode/" + code ;
        try {
            String filter = "code=" + code;
            List<TjDataSave> list = tjDataSaveService.search(filter);
            return ObjEnvelop.getSuccess("查询成功",list.size() > 0);
        } catch (Exception e) {
            e.getMessage();
        }
        return  failed("查询失败");
    }
}

+ 238 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDataSourceController.java

@ -0,0 +1,238 @@
package com.yihu.jw.basic.agadmin.controller.quota;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.constants.SessionAttributeKeys;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by llh on 2017/5/9.
 */
@RestController
@RequestMapping("/tjDataSource")
public class TjDataSourceController extends EnvelopRestEndpoint {
    /**
     * 数据资源
     * @param model
     * @return
     */
    @RequestMapping("initial")
    public String initial(Model model) {
        model.addAttribute("contentPage", "/report/zhibiao/dataSource");
        return "pageView";
    }
    //查询
    @RequestMapping("/getTjDataSource")
    @ResponseBody
    public Object searchTjDataSource(String name,String searchParm, int page, int rows){
        String url = "/tj/getTjDataSourceList";
        String resultStr = "";
        Envelop envelop = new Envelop();
        Map<String, Object> params = new HashMap<>();
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(name)) {
            stringBuffer.append("name?" + name );
        }
        if (!StringUtils.isEmpty(searchParm)) {
            stringBuffer.append("name?" + searchParm );
        }
        String filters = stringBuffer.toString();
        if (!StringUtils.isEmpty(filters)) {
            params.put("filters", filters);
        }
        params.put("page", page);
        params.put("size", rows);
        try {
            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
            return resultStr;
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 新增修改
     * @param tjDataSourceModelJsonData
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "updateTjDataSource", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object updateTjDataSource(String tjDataSourceModelJsonData, HttpServletRequest request) throws IOException {
        String url = "/tj/addTjDataSource";
        String resultStr = "";
        System.out.println();
        Envelop result = new Envelop();
        UsersModel userDetailModel = getCurrentUserRedis(request);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        String[] strings = URLDecoder.decode(tjDataSourceModelJsonData, "UTF-8").split(";");
        TjDataSourceModel detailModel = toModel(strings[0], TjDataSourceModel.class);
        RestTemplates templates = new RestTemplates();
        try {
            if (!StringUtils.isEmpty(detailModel.getId())) {
                Long tjDataSourceId = detailModel.getId();
                resultStr = templates.doGet(comUrl + "/tj/getTjDataSourceById/" + tjDataSourceId);
                Envelop envelop = getEnvelop(resultStr);
                if (envelop.isSuccessFlg()) {
                    TjDataSourceModel updateTjDataSource = getEnvelopModel(envelop.getObj(), TjDataSourceModel.class);
                    updateTjDataSource.setCode(detailModel.getCode());
                    updateTjDataSource.setName(detailModel.getName());
                    updateTjDataSource.setType(detailModel.getType());
                    updateTjDataSource.setStatus(detailModel.getStatus());
                    updateTjDataSource.setRemark(detailModel.getRemark());
                    updateTjDataSource.setUpdateUser(userDetailModel.getId());
                    updateTjDataSource.setUpdateUserName(userDetailModel.getRealName());
                    params.add("model", toJson(updateTjDataSource));
                    resultStr = templates.doPost(comUrl + url, params);
                } else {
                    result.setSuccessFlg(false);
                    result.setErrorMsg(envelop.getErrorMsg());
                    return result;
                }
            } else {
                detailModel.setCreateUser(userDetailModel.getId());
                detailModel.setCreateUserName(userDetailModel.getRealName());
                params.add("model", toJson(detailModel));
                resultStr = templates.doPost(comUrl + url, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
        return resultStr;
    }
    /**
     * 删除消息
     * @param tjDataSourceId
     * @return
     */
    @RequestMapping("deleteTjDataSource")
    @ResponseBody
    public Object deleteTjDataSource(Long tjDataSourceId) {
        String url = "/tj/deletetTjDataSource" ;
        String resultStr = "";
        Envelop result = new Envelop();
        Map<String, Object> params = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        params.put("id", tjDataSourceId);
        try {
            resultStr = HttpClientUtil.doDelete(comUrl + url, params, username, password);
            result = mapper.readValue(resultStr, Envelop.class);
            if (result.isSuccessFlg()) {
                result.setSuccessFlg(true);
            } else {
                result.setSuccessFlg(false);
                result.setErrorMsg("删除失败");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 根据id获取消息
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("getTjDataSourceById")
    @ResponseBody
    public TjDataSourceModel getTjQuotaById(Model model, Long id ) {
        String url ="/tj/getTjDataSourceById/" +id;
        String resultStr = "";
        Envelop envelop = new Envelop();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        TjDataSourceModel detailModel = null;
        try {
            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
            Envelop ep = getEnvelop(resultStr);
            detailModel = toModel(toJson(ep.getObj()),TjDataSourceModel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detailModel;
    }
    /**
     * 校验name是否唯一,true已存在
     * @param name
     * @return
     */
    @RequestMapping("hasExistsName")
    @ResponseBody
    public boolean hasExistsName(String name) {
        String url = "/tj/tjDataSourceExistsName/" + name ;
        String resultStr = "";
        Envelop result = new Envelop();
        Map<String, Object> params = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        params.put("name", name);
        try {
            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
            if (resultStr.equals("true")) {
                return  true;
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return  false;
    }
    /**
     * 校验code是否唯一
     * @param code
     * @return
     */
    @RequestMapping("hasExistsCode")
    @ResponseBody
    public boolean hasExistsCode(String code) {
        String url = "/tj/tjDataSourceExistsCode/" + code ;
        String resultStr = "";
        Envelop result = new Envelop();
        Map<String, Object> params = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        params.put("code", code);
        try {
            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
            if (resultStr.equals("true")) {
                return  true;
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return  false;
    }
}

+ 259 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDimensionMainController.java

@ -0,0 +1,259 @@
package com.yihu.jw.basic.agadmin.controller.quota;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.quota.service.TjDimensionMainService;
import com.yihu.jw.entity.ehr.quota.TjDimensionMain;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
/**
 * Created by llh on 2017/5/9.
 */
@RestController
@RequestMapping("/tjDimensionMain")
public class TjDimensionMainController extends EnvelopRestEndpoint {
    @Autowired
    TjDimensionMainService tjDimensionMainService;
    //查询统计主维度
    @RequestMapping("/getTjDimensionMain")
    public Object searchTjDimensionMain(String name, int page, int rows){
        String url = "/tj/getTjDimensionMainList";
        String resultStr = "";
        Envelop envelop = new Envelop();
        Map<String, Object> params = new HashMap<>();
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(name)) {
            stringBuffer.append("name?" + name );
        }
        String filters = stringBuffer.toString();
        if (!StringUtils.isEmpty(filters)) {
            params.put("filters", filters);
        }
        params.put("page", page);
        params.put("size", rows);
        try {
            PageEnvelop PageEnvelop = new PageEnvelop();
            List<TjDimensionMain> qtjDimensionMainList = tjDimensionMainService.search(null, filters, null, page, rows);
            if(qtjDimensionMainList != null){
                PageEnvelop.setDetailModelList(qtjDimensionMainList);
                PageEnvelop.setTotalCount((int)tjDimensionMainService.getCount(filters));
                PageEnvelop.setStatus(200);
                PageEnvelop.setCurrPage(page);
                PageEnvelop.setPageSize(rows);
            }else{
                PageEnvelop.setStatus(200);
                PageEnvelop.setMessage("查询无数据");
                PageEnvelop.setTotalCount(0);
            }
            return PageEnvelop;
        } catch (Exception ex) {
            ex.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 新增修改
     * @param tjDimensionMainModelJsonData
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "updateTjDimensionMain", produces = "text/html;charset=UTF-8")
    public Object updateTjDimensionMain(String tjDimensionMainModelJsonData, HttpServletRequest request) throws IOException {
        String url = "/tj/tjDimensionMain";
        String resultStr = "";
        System.out.println();
        String[] strings = URLDecoder.decode(tjDimensionMainModelJsonData, "UTF-8").split(";");
        TjDimensionMain detailModel = objectMapper.readValue(strings[0], TjDimensionMain.class);
        try {
            if (!StringUtils.isEmpty(detailModel.getId())) {
                Long id = detailModel.getId();
                TjDimensionMain updateTjDimensionMain = tjDimensionMainService.getTjDimensionMain(id);
                if (updateTjDimensionMain!=null) {
                    updateTjDimensionMain.setCode(detailModel.getCode());
                    updateTjDimensionMain.setName(detailModel.getName());
                    updateTjDimensionMain.setType(detailModel.getType());
                    updateTjDimensionMain.setStatus(detailModel.getStatus());
                    updateTjDimensionMain.setRemark(detailModel.getRemark());
                    updateTjDimensionMain.setUpdateTime(new Date());
                    tjDimensionMainService.save(updateTjDimensionMain);
                    return ObjEnvelop.getSuccess("保存成功",updateTjDimensionMain);
                } else {
                    return failed("参数错误");
                }
            } else {
                detailModel.setCreateTime(new Date());
                tjDimensionMainService.save(detailModel);
                return ObjEnvelop.getSuccess("保存成功",detailModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 删除消息
     * @param tjDimensionMainId
     * @return
     */
    @RequestMapping("deleteTjDimensionMain")
    public Object deleteTjDimensionMain(Long tjDimensionMainId) {
        String url = "/tj/tjDimensionMain";
        try {
            TjDimensionMain tjDimensionMain = tjDimensionMainService.getTjDimensionMain(tjDimensionMainId);
            tjDimensionMain.setStatus(-1);
            tjDimensionMainService.save(tjDimensionMain);
            return ObjEnvelop.getSuccess("主维度删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
        }
    }
    /**
     * 根据id获取消息
     * @param id
     * @return
     */
    @RequestMapping("getTjDimensionMainByID")
    public Envelop getTjDimensionMainByID(Long id ) {
        String url ="/tj/tjDimensionMainId/" +id;
        try {
            TjDimensionMain updateTjDimensionMain = tjDimensionMainService.getTjDimensionMain(id);
            return ObjEnvelop.getSuccess("查询成功",updateTjDimensionMain);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
    /**
     * 校验名称是否唯一
     * @param name
     * @return
     */
    @RequestMapping("isNameExists")
    public Envelop isNameExists(String name) {
        String url = "/tj/tjDimensionMainName" ;
        try {
            String filter = "name=" + name;
            List<TjDimensionMain> tjDimensionMains = tjDimensionMainService.search(filter);
            return ObjEnvelop.getSuccess("",tjDimensionMains.size() >0);
        } catch (Exception e) {
            e.getMessage();
        }
        return  failed("查询失败");
    }
    /**
     * 校验code是否唯一
     * @param code
     * @return
     */
    @RequestMapping("isCodeExists")
    public Envelop isCodeExists(String code) {
        String url = "/tj/tjDimensionMainCode" ;
        try {
            String filter = "code=" + code;
            List<TjDimensionMain> tjDimensionMains = tjDimensionMainService.search(filter);
            return ObjEnvelop.getSuccess("",tjDimensionMains.size() >0);
        } catch (Exception e) {
            e.getMessage();
        }
        return  failed("查询失败");
    }
//    @RequestMapping("/getTjDimensionMainInfo")
//    public Envelop getTjDimensionMainInfo(String quotaCode, String name, int page, int rows){
//        String url = "/tj/getTjDimensionMainInfoList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        StringBuffer mainFilter = new StringBuffer("status=1");
//        if (!StringUtils.isEmpty(quotaCode)) {
//            params.put("filter", "quotaCode=" + quotaCode);
//        }
//        if (!StringUtils.isEmpty(name)) {
//            mainFilter.append("name?" + name + " g1;code?" + name + " g1;");
//        }
//        String filters = mainFilter.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            ListResult listResult = tjDimensionMainClient.search(fields, filters, sorts, size, page);
//
//            List<TjDimensionMainModel> mainModelList  = new ArrayList<>();
//            if(listResult.getTotalCount() != 0){
//                List<Map<String,Object>> modelList = listResult.getDetailModelList();
//                for(Map<String,Object> map : modelList){
//                    TjDimensionMainModel tjDimensionMainModel = objectMapper.convertValue(map,TjDimensionMainModel.class);
//                    mainModelList.add(tjDimensionMainModel);
//                }
//                ListResult listResult2 = tjQuotaDimensionMainClient.search(fields, filter, sorts, size, page);
//                List<TjQuotaDimensionMainModel> mainModelList2  = new ArrayList<>();
//                if(listResult2.getTotalCount() != 0) {
//                    List<Map<String, Object>> modelList2 = listResult2.getDetailModelList();
//                    for (Map<String, Object> map : modelList2) {
//                        TjQuotaDimensionMainModel tjQuotaDimensionMainModel = objectMapper.convertValue(map, TjQuotaDimensionMainModel.class);
//                        TjDimensionMain tjDimensionMain = tjDimensionMainClient.getTjDimensionMain(tjQuotaDimensionMainModel.getMainCode());
//                        if (tjDimensionMain != null) {
//                            tjQuotaDimensionMainModel.setName(tjDimensionMain.getName());
//                        }
//                        mainModelList2.add(tjQuotaDimensionMainModel);
//                    }
//                }
//                List<String> list = getTjQuotaDimensionMainOfMainCode(filter, sorts);
//                for (int i=0; i<mainModelList.size(); i++) {
//                    if (list.contains(mainModelList.get(i).getCode())) {
//                        mainModelList.get(i).setChecked(true);
//                    } else {
//                        mainModelList.get(i).setChecked(false);
//                    }
//                }
//                Envelop result = getResult(mainModelList, listResult.getTotalCount(), listResult.getCurrPage(), listResult.getPageSize());
//                result.setObj(mainModelList2);
//                return result;
//            }else{
//                Envelop envelop = new Envelop();
//                return envelop;
//            }
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
}

+ 258 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjDimensionSlaveController.java

@ -0,0 +1,258 @@
//package com.yihu.jw.basic.agadmin.controller.quota;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.constants.SessionAttributeKeys;
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.util.http.HttpClientUtil;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.SessionAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.net.URLDecoder;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by llh on 2017/5/9.
// */
//@RestController
//@RequestMapping("/tjDimensionSlave")
//public class TjDimensionSlaveController extends EnvelopRestEndpoint {
//
//
//
//    //查询
//    @RequestMapping("/getTjDimensionSlave")
//    @ResponseBody
//    public Object searchTjDimensionSlave(String name, int page, int rows){
//        String url = "/tj/getTjDimensionSlaveList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!StringUtils.isEmpty(name)) {
//            stringBuffer.append("name?" + name );
//        }
//        String filters = stringBuffer.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//
//
//    /**
//     * 新增修改
//     * @param tjDimensionSlaveModelJsonData
//     * @param request
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "updateTjDimensionSlave", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Object updateTjDimensionSlave(String tjDimensionSlaveModelJsonData, HttpServletRequest request) throws IOException {
//
//        String url = "/tj/tjDimensionSlave";
//        String resultStr = "";
//        System.out.println();
//        Envelop result = new Envelop();
//        UsersModel userDetailModel = getCurrentUserRedis(request);
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        String[] strings = URLDecoder.decode(tjDimensionSlaveModelJsonData, "UTF-8").split(";");
//        TjDimensionSlaveModel detailModel = toModel(strings[0], TjDimensionSlaveModel.class);
//        RestTemplates templates = new RestTemplates();
//
//        try {
//            if (!StringUtils.isEmpty(detailModel.getId())) {
//                Long id = detailModel.getId();
//                resultStr = templates.doGet(comUrl + "/tj/tjDimensionSlaveId/" + id);
//                Envelop envelop = getEnvelop(resultStr);
//                if (envelop.isSuccessFlg()) {
//                    TjDimensionSlaveModel updateTjDimensionSlave = getEnvelopModel(envelop.getObj(), TjDimensionSlaveModel.class);
//
//                    updateTjDimensionSlave.setCode(detailModel.getCode());
//                    updateTjDimensionSlave.setName(detailModel.getName());
//                    updateTjDimensionSlave.setType(detailModel.getType());
//                    updateTjDimensionSlave.setStatus(detailModel.getStatus());
//                    updateTjDimensionSlave.setRemark(detailModel.getRemark());
//                    updateTjDimensionSlave.setUpdateUser(userDetailModel.getId());
//                    updateTjDimensionSlave.setUpdateUserName(userDetailModel.getRealName());
//                    params.add("model", toJson(updateTjDimensionSlave));
//
//                    resultStr = templates.doPost(comUrl + url, params);
//                } else {
//                    result.setSuccessFlg(false);
//                    result.setErrorMsg(envelop.getErrorMsg());
//                    return result;
//                }
//            } else {
//                detailModel.setCreateUser(userDetailModel.getId());
//                detailModel.setCreateUserName(userDetailModel.getRealName());
//                params.add("model", toJson(detailModel));
//                resultStr = templates.doPost(comUrl + url, params);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return resultStr;
//    }
//
//    /**
//     * 删除消息
//     * @param tjDimensionSlaveId
//     * @return
//     */
//    @RequestMapping("deleteTjDimensionSlave")
//    @ResponseBody
//    public Object deleteTjDimensionSlave(Long tjDimensionSlaveId) {
//        String url = "/tj/tjDimensionSlave";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//
//        params.put("id", tjDimensionSlaveId);
//        try {
//            resultStr = HttpClientUtil.doDelete(comUrl + url, params, username, password);
//            result = mapper.readValue(resultStr, Envelop.class);
//            if (result.isSuccessFlg()) {
//                result.setSuccessFlg(true);
//            } else {
//                result.setSuccessFlg(false);
//                result.setErrorMsg("删除失败");
//            }
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//
//    /**
//     * 根据id获取消息
//     * @param model
//     * @param id
//     * @return
//     */
//    @RequestMapping("getTjDimensionSlaveById")
//    @ResponseBody
//    public TjDimensionSlaveModel getTjDimensionSlaveById(Model model, Long id ) {
//        String url ="/tj/tjDimensionSlaveId/" +id;
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", id);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            Envelop ep = getEnvelop(resultStr);
//            TjDimensionSlaveModel detailModel = toModel(toJson(ep.getObj()),TjDimensionSlaveModel.class);
//            return detailModel;
//        } catch (Exception e) {
//            return null;
//        }
//    }
//
//    /**
//     * 校验名称是否唯一
//     * @param name
//     * @return
//     */
//    @RequestMapping("isNameExists")
//    @ResponseBody
//    public boolean isNameExists(String name) {
//        String url = "/tj/tjDimensionSlaveName" ;
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//        params.put("name", name);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if (resultStr.equals("true")) {
//                return  true;
//            } else {
//
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return  false;
//    }
//
//    /**
//     * 校验code是否唯一
//     * @param code
//     * @return
//     */
//    @RequestMapping("isCodeExists")
//    @ResponseBody
//    public boolean isCodeExists(String code) {
//        String url = "/tj/tjDimensionSlaveCode" ;
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//        params.put("code", code);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if (resultStr.equals("true")) {
//                return  true;
//            } else {
//
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return  false;
//    }
//
//    @RequestMapping("/getTjDimensionSlaveInfo")
//    @ResponseBody
//    public Object getTjDimensionSlaveInfo(String quotaCode, String name, int page, int rows){
//        String url = "/tj/getTjDimensionSlaveInfoList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        StringBuffer slaveFilter = new StringBuffer("status=1");
//        if (!StringUtils.isEmpty(quotaCode)) {
//            params.put("filter", "quotaCode=" + quotaCode);
//        }
//        if (!StringUtils.isEmpty(name)) {
//            slaveFilter.append("name?" + name + " g1;code?" + name + " g1;");
//        }
//        String filters = slaveFilter.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//}

+ 947 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaController.java

@ -0,0 +1,947 @@
//package com.yihu.jw.basic.agadmin.controller.quota;
//
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.fasterxml.jackson.databind.ObjectMapper;
//
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.util.http.HttpClientUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.SessionAttributes;
//import org.springframework.web.client.RestClientException;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.*;
//import java.net.URLDecoder;
//import java.util.*;
//
///**
// * Created by Administrator on 2017/6/13.
// */
//@RestController
//@RequestMapping("/tjQuota")
//public class TjQuotaController extends EnvelopRestEndpoint {
//
//
//    @RequestMapping("/getTjQuota")
//    @ResponseBody
//    public Object searchTjQuota(String name, Integer quotaType, int page, int rows) {
//        String url = "/tj/getTjQuotaList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("filters", "");
//        StringBuffer stringBuffer = new StringBuffer();
//        stringBuffer.append("status=1;");
//        if (!StringUtils.isEmpty(name)) {
//            stringBuffer.append("name?" + name.trim() + " g1;code?" + name.trim() + " g1;");
//        }
//        if (!StringUtils.isEmpty(quotaType)) {
//            stringBuffer.append("quotaType=" + quotaType + ";");
//        } /*else {
//            stringBuffer.append("quotaType=-1");
//        }*/
//        String filters = stringBuffer.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 新增修改
//     *
//     * @param tjQuotaModelJsonData
//     * @param request
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "updateTjDataSource", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Object updateTjQuota(String tjQuotaModelJsonData, HttpServletRequest request) throws IOException {
//
//        String url = "/tj/addTjQuota/";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        UsersModel userDetailModel = getCurrentUserRedis(request);
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        String[] strings = URLDecoder.decode(tjQuotaModelJsonData, "UTF-8").split(";");
//        TjQuotaModel detailModel = toModel(strings[0], TjQuotaModel.class);
//        RestTemplates templates = new RestTemplates();
//
//        try {
//            if (!StringUtils.isEmpty(detailModel.getId())) {
//                Long tjQuotaId = detailModel.getId();
//                resultStr = templates.doGet(comUrl + "/tj/getTjQuotaById/" + tjQuotaId);
//                Envelop envelop = getEnvelop(resultStr);
//                if (envelop.isSuccessFlg()) {
//                    TjQuotaModel updateTjQuota = getEnvelopModel(envelop.getObj(), TjQuotaModel.class);
//
//                    updateTjQuota.setResultGetType(detailModel.getResultGetType());
//                    updateTjQuota.setCode(detailModel.getCode());
//                    updateTjQuota.setName(detailModel.getName());
//                    updateTjQuota.setCron(detailModel.getCron());
//                    updateTjQuota.setJobStatus(detailModel.getJobStatus());
//                    updateTjQuota.setExecType(detailModel.getExecType());
//                    updateTjQuota.setExecTime(detailModel.getExecTime());
//                    updateTjQuota.setJobClazz(detailModel.getJobClazz());
//                    updateTjQuota.setQuotaType(detailModel.getQuotaType());
//                    updateTjQuota.setDataLevel(detailModel.getDataLevel());
//                    updateTjQuota.setRemark(detailModel.getRemark());
//                    updateTjQuota.setUpdateUser(userDetailModel.getId());
//                    updateTjQuota.setUpdateUserName(userDetailModel.getRealName());
//                    updateTjQuota.setTjQuotaDataSaveModel(detailModel.getTjQuotaDataSaveModel());
//                    updateTjQuota.setTjQuotaDataSourceModel(detailModel.getTjQuotaDataSourceModel());
//                    updateTjQuota.setTjQuotaChartModel(detailModel.getTjQuotaChartModel());
//                    params.add("model", toJson(updateTjQuota));
//
//                    resultStr = templates.doPost(comUrl + url, params);
//                } else {
//                    result.setSuccessFlg(false);
//                    result.setErrorMsg(envelop.getErrorMsg());
//                    return result;
//                }
//            } else {
//                detailModel.setCreateUser(userDetailModel.getId());
//                detailModel.setCreateUserName(userDetailModel.getRealName());
//                params.add("model", toJson(detailModel));
//                resultStr = templates.doPost(comUrl + url, params);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return resultStr;
//    }
//
//    /**
//     * 删除
//     *
//     * @param tjQuotaId
//     * @return
//     */
//    @RequestMapping("deleteTjDataSave")
//    @ResponseBody
//    public Object deleteTjQuota(Long tjQuotaId) {
//        String url = "/tj/deleteTjQuota";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//
//        //判断资源视图中有没有用到此视图,有用到 不允许删除
//        String resQuotaUrl = "/resourceQuota/searchByQuotaId";
//
//        try {
//            params.put("quotaId", tjQuotaId);
//            resultStr = HttpClientUtil.doGet(comUrl + resQuotaUrl, params, username, password);
//            result = mapper.readValue(resultStr, Envelop.class);
//            if (result.getObj() != null) {
//                result.setSuccessFlg(false);
//                result.setErrorMsg("指标在视图中被使用暂时不能删除,若要删除先解除资源视图中指标关系");
//                return result;
//            }
//
//            params.clear();
//            params.put("id", tjQuotaId);
//            resultStr = HttpClientUtil.doDelete(comUrl + url, params, username, password);
//            result = mapper.readValue(resultStr, Envelop.class);
//            if (result.isSuccessFlg()) {
//                result.setSuccessFlg(true);
//            } else {
//                result.setSuccessFlg(false);
//                result.setErrorMsg("删除失败");
//            }
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 根据id获取消息
//     *
//     * @param model
//     * @param id
//     * @return
//     */
//    @RequestMapping("getTjQuotaById")
//    @ResponseBody
//    public Object getTjQuotaById(Model model, Long id) {
//        String url = "/tj/getTjQuotaById/" + id;
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", id);
//        TjQuotaModel detailModel = null;
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            Envelop ep = getEnvelop(resultStr);
//            detailModel = toModel(toJson(ep.getObj()), TjQuotaModel.class);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return detailModel;
//    }
//
//    /**
//     * 校验name是否唯一,true已存在
//     *
//     * @param name
//     * @return
//     */
//    @RequestMapping("hasExistsName")
//    @ResponseBody
//    public boolean hasExistsName(String name) {
//        String url = "/tj/tjQuotaExistsName/" + name;
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//        params.put("name", name);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if (resultStr.equals("true")) {
//                return true;
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return false;
//    }
//
//    /**
//     * 校验code是否唯一
//     *
//     * @param code
//     * @return
//     */
//    @RequestMapping("hasExistsCode")
//    @ResponseBody
//    public boolean hasExistsCode(String code) {
//        String url = "/tj/tjQuotaExistsCode/" + code;
//        String resultStr = "";
//        Envelop result = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        ObjectMapper mapper = new ObjectMapper();
//        params.put("code", code);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if (resultStr.equals("true")) {
//                return true;
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return false;
//    }
//
//    /**
//     * 初始执行(全量统计)
//     */
//    @RequestMapping("firstExecuteQuota")
//    @ResponseBody
//    public Object firstExecuteQuota(Long tjQuotaId) {
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", tjQuotaId);
//        try {
//            String url = "/job/firstExecuteQuota";
//            String resultStr = HttpClientUtil.doPost(comUrl + url, params, username, password);
//            envelop = objectMapper.readValue(resultStr, Envelop.class);
//            return envelop;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 执行指标
//     */
//    @RequestMapping("execuQuota")
//    @ResponseBody
//    public Object execuQuota(Long tjQuotaId, String startDate, String endDate) {
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", tjQuotaId);
//        if (!StringUtils.isEmpty(startDate)) {
//            params.put("startDate", startDate);
//        }
//        if (!StringUtils.isEmpty(endDate)) {
//            params.put("endDate", endDate);
//        }
//        try {
//            String url = "/job/execuJob";
//            String resultStr = HttpClientUtil.doPost(comUrl + url, params, username, password);
//            envelop = objectMapper.readValue(resultStr, Envelop.class);
//            return envelop;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 指标结果页
//     *
//     * @param model
//     * @return
//     */
//    @RequestMapping("initialResult")
//    public String initialResult(Model model, long tjQuotaId, String quotaCode, String quotaType, String name) throws Exception {
//        model.addAttribute("contentPage", "/report/zhibiao/resultIndex");
//        model.addAttribute("id", tjQuotaId);
//        model.addAttribute("quotaType", quotaType);
//        model.addAttribute("name", name);
//        String urlSlave = "/tj/getDimensionSlaveByQuotaCode";
//        Map<String, Object> params = new HashMap<>();
//        params.put("quotaCode", quotaCode);
//        Envelop result = null;
//        try {
//            String resultStr = HttpClientUtil.doGet(comUrl + urlSlave, params, username, password);
//            result = objectMapper.readValue(resultStr, Envelop.class);
//            if (result.isSuccessFlg() && result.getDetailModelList().size() > 0) {
//                List<HashMap> slaveModelList = result.getDetailModelList();
//                if (slaveModelList != null && slaveModelList.size() > 0) {
//                    int num = 1;
//                    for (HashMap map : slaveModelList) {
//                        TjQuotaDimensionSlaveModel quotaDimensionSlaveModel = objectMapper.convertValue(map, TjQuotaDimensionSlaveModel.class);
//                        RestTemplates templates = new RestTemplates();
//                        params.clear();
//                        params.put("code", quotaDimensionSlaveModel.getSlaveCode());
//                        resultStr = HttpClientUtil.doGet(comUrl + "/tj/getTjDimensionSlaveByCode", params, username, password);
//                        result = objectMapper.readValue(resultStr, Envelop.class);
//                        if (result.isSuccessFlg()) {
//                            TjDimensionSlaveModel tjDimensionSlaveModel = objectMapper.convertValue(result.getObj(), TjDimensionSlaveModel.class);
//                            model.addAttribute("slaveKey" + num + "Name", tjDimensionSlaveModel.getName());
//                            num++;
//                        }
//                    }
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "emptyView";
//    }
//
//
//    /**
//     * 指标执行结果
//     *
//     * @param tjQuotaId
//     * @return
//     */
//    @RequestMapping("selectQuotaResult")
//    @ResponseBody
//    public Object selectQuotaResult(Long tjQuotaId, int page, int rows,
//                                    String startTime, String endTime, String orgName,
//                                    String province, String city, String district,String res, HttpServletRequest request) {
//        Envelop result = new Envelop();
//        String resultStr = "";
//        String url = "/tj/tjGetQuotaResult";
//        try {
//            Map<String, Object> filters = new HashMap<>();
//            filters.put("startTime", startTime);
//            filters.put("endTime", endTime);
//            filters.put("org", orgName);
//            filters.put("province", province);
//            filters.put("town", city);
//            filters.put("district", district);
//             // 结果大于0
//            filters.put("result", res);
//            Map<String, Object> params = new HashMap<>();
//            List<String> userOrgList = getUserOrgSaasListRedis(request);
//            params.put("userOrgList", userOrgList);
//            params.put("id", tjQuotaId);
//            params.put("pageNo", page);
//            params.put("pageSize", rows);
//            params.put("filters", objectMapper.writeValueAsString(filters));
//            ObjectMapper mapper = new ObjectMapper();
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            result = mapper.readValue(resultStr, Envelop.class);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 指标日志查询
//     *
//     * @param model
//     * @return
//     */
//    @RequestMapping("initialQuotaLog")
//    public String initialQuotaLog(Model model, String quotaCode, String quotaType, String name) {
//        model.addAttribute("contentPage", "/report/zhibiao/zhiBiaoLogIndex");
//        model.addAttribute("quotaCode", quotaCode);
//        model.addAttribute("quotaType", quotaType);
//        model.addAttribute("name", name);
//        return "emptyView";
//    }
//
//    /**
//     * 获取指标日志信息
//     *
//     * @param
//     * @return
//     */
//    @RequestMapping("queryQuotaLog")
//    @ResponseBody
//    public Object queryQuotaLog(String quotaCode, String startTime, String endTime, int page, int rows) throws Exception {
//        String url = "/tj/getTjQuotaLogList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//
//        params.put("startTime", startTime);
//        params.put("endTime", endTime);
//        params.put("quotaCode", quotaCode);
//        params.put("fields", "");
//        params.put("sorts", "");
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 获取quotaCode查询是否配置维度
//     *
//     * @param
//     * @return
//     */
//    @RequestMapping("hasConfigDimension")
//    @ResponseBody
//    public boolean hasConfigDimension(String quotaCode) throws Exception {
//        String url = "/tj/hasConfigDimension";
//        String resultStr = "";
//        Map<String, Object> params = new HashMap<>();
//
//        params.put("quotaCode", quotaCode);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            if (resultStr.equals("true")) {
//                return true;
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return false;
//    }
//
//
//    //带检索分页的查找指标方法,用于下拉框
//    @RequestMapping("/rsQuota")
//    @ResponseBody
//    public Object searchRsQuota(String searchParm, int page, int rows) {
//        String url = "/tj/getTjQuotaList";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!StringUtils.isEmpty(searchParm)) {
//            stringBuffer.append("name?" + searchParm + ";");
//        }
//        params.put("filters", "");
//        String filters = stringBuffer.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            String envelopStrGet = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            Envelop envelopGet = objectMapper.readValue(envelopStrGet, Envelop.class);
//            List<TjQuotaModel> tjQuotaModelList = new ArrayList<>();
//            List<Map> list = new ArrayList<>();
//            if (envelopGet.isSuccessFlg()) {
//                tjQuotaModelList = (List<TjQuotaModel>) getEnvelopList(envelopGet.getDetailModelList(), new ArrayList<TjQuotaModel>(), TjQuotaModel.class);
//                for (TjQuotaModel m : tjQuotaModelList) {
//                    Map map = new HashMap<>();
//                    map.put("id", m.getCode());
//                    map.put("name", m.getName());
//                    list.add(map);
//                }
//                envelopGet.setDetailModelList(list);
//                return envelopGet;
//            }
//            return envelop;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//
//    @RequestMapping("/getTjQuotaChartList")
//    @ResponseBody
//    public Object getQuotaChartList(String quotaCode, String name, int dictId, int page, int rows) {
//        String url = "/tj/getTjQuotaChartList";
//        String resultStr = "";
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("filters", "");
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!StringUtils.isEmpty(quotaCode)) {
//            stringBuffer.append("quotaCode=" + quotaCode);
//        }
//        if (!StringUtils.isEmpty(name)) {
//            stringBuffer.append("value?" + name);
//        }
//        String filters = stringBuffer.toString();
//        if (!StringUtils.isEmpty(filters)) {
//            params.put("filters", filters);
//        }
//        String filter = "";
//        if (!StringUtils.isEmpty(dictId)) {
//            filter = "dictId=" + dictId;
//        }
//        params.put("dictfilter", filter);
//        params.put("page", page);
//        params.put("size", rows);
//        try {
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            return resultStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//    /**
//     * 添加主维度子表
//     *
//     * @param jsonModel 维度子表信息的json串
//     * @param request
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "addTjQuotaChart", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Object addTjQuotaChart(String quotaCode, String jsonModel, HttpServletRequest request) throws IOException {
//        String url = "/tj/batchTjQuotaChart";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        params.add("model", jsonModel);
//        RestTemplates templates = new RestTemplates();
//        try {
//            resultStr = templates.doPost(comUrl + url, params);
//        } catch (RestClientException e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return resultStr;
//    }
//
//    /**
//     * 指标文件导入
//     *
//     * @param file
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     */
//    private static final String parentFile = "tjQuotaDataSet";
//
//    @RequestMapping(value = "import")
//    @ResponseBody
//    public void importData(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        try {
//            UsersModel user = getCurrentUserRedis(request);
//            writerResponse(response, 1 + "", "l_upd_progress");
//            request.setCharacterEncoding("UTF-8");
//            TjQuotaMsgReader excelReader = new TjQuotaMsgReader();
//            excelReader.read(file.getInputStream());
//            //指标
//            List<TjQuotaMsg> errorLs = excelReader.getErrorLs();
//            List<TjQuotaMsg> correctLs = excelReader.getCorrectLs();
//            //主维度
//            List<TjQuotaDMainMsg> quotaMainErrorLs = excelReader.getQuotaMainErrorLs();
//            List<TjQuotaDMainMsg> quotaMainCorrectLs = excelReader.getQuotaMainCorrectLs();
//            //细维度
//            List<TjQuotaDSlaveMsg> quotaSlaveErrorLs = excelReader.getQuotaSlaveErrorLs();
//            List<TjQuotaDSlaveMsg> quotaSlaveCorrectLs = excelReader.getQuotaSlaveCorrectLs();
//            writerResponse(response, 35 + "", "l_upd_progress");
//
//            Map<String, Object> LsMap = validate(user, excelReader, errorLs, correctLs, quotaMainErrorLs, quotaMainCorrectLs, quotaSlaveErrorLs, quotaSlaveCorrectLs);
//            writerResponse(response, 55 + "", "l_upd_progress");
//
//            Map rs = new HashMap<>();
//            //输出错误信息
//            if (errorLs.size() > 0 || quotaMainErrorLs.size() > 0 || quotaSlaveErrorLs.size() > 0) {
//                String eFile = TemPath.createFileName(user.getLoginCode(), "e", parentFile, ".xls");
//                new TjQuotaMsgWriter().write(new File(TemPath.getFullPath(eFile, parentFile)), errorLs, quotaMainErrorLs, quotaSlaveErrorLs);
//                rs.put("eFile", new String[]{eFile.substring(0, 10), eFile.substring(11, eFile.length())});
//            }
//            writerResponse(response, 65 + "", "l_upd_progress");
//
//            if (LsMap.size() > 0) {
//                saveData(LsMap);
//            }
//            if (errorLs.size() == 0 && quotaMainErrorLs.size() == 0 && quotaSlaveErrorLs.size() == 0){
//                writerResponse(response, 100 + ",'suc'", "l_upd_progress");
//            } else {
//                writerResponse(response, 100 + ",'" + toJson(rs) + "'", "l_upd_progress");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            writerResponse(response, "-1", "l_upd_progress");
//        }
//    }
//
//    protected void writerResponse(HttpServletResponse response, String body, String client_method) throws IOException {
//        StringBuffer sb = new StringBuffer();
//        sb.append("<script type=\"text/javascript\">//<![CDATA[\n");
//        sb.append("     parent.").append(client_method).append("(").append(body).append(");\n");
//        sb.append("//]]></script>");
//
//        response.setContentType("text/html;charset=UTF-8");
//        response.addHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
//        response.setHeader("Cache-Control", "pre-check=0,post-check=0");
//        response.setDateHeader("Expires", 0);
//        response.getWriter().write(sb.toString());
//        response.flushBuffer();
//    }
//
//    /**
//     * 验证指标编码、名称、指标分类、主维度、细维度
//     *
//     * @param excelReader         待验证的数据
//     * @param errorLs             指标错误数据
//     * @param correctLs           指标正常数据
//     * @param quotaMainErrorLs    主维度错误数据
//     * @param quotaMainCorrectLs  主维度正常数据
//     * @param quotaSlaveErrorLs   细维度错误数据
//     * @param quotaSlaveCorrectLs 细维度正常数据
//     * @return
//     * @throws Exception
//     */
//    private Map<String,Object> validate(UsersModel user,TjQuotaMsgReader excelReader,
//                          List<TjQuotaMsg> errorLs, List<TjQuotaMsg> correctLs ,
//                           List<TjQuotaDMainMsg>  quotaMainErrorLs ,List<TjQuotaDMainMsg>  quotaMainCorrectLs ,
//                           List<TjQuotaDSlaveMsg>  quotaSlaveErrorLs ,List<TjQuotaDSlaveMsg>  quotaSlaveCorrectLs) throws Exception {
//        List saveLs = new ArrayList<>();
//        List quotaMainLs = new ArrayList<>();
//        List quotaSlaveLs = new ArrayList<>();
//        //验证指标编码是否存在
//        Set<String> quotaCodes = findExistCodeOrName("code", excelReader.getRepeat().get("code"));
//        //验证指标名称是否存在
//        Set<String> quotaNames = findExistCodeOrName("name", excelReader.getRepeat().get("name"));
//        //根据指标类型名称获取指标类型id
//        Map<String, String> quotaTypes = findExistQuotaType(excelReader.getRepeat().get("quotaType"));
//        //判断主维度编码是否存在
//        Set<String> mainCodes = findExistCodeOrName("mainCode", excelReader.getQuotaMainRepeat().get("mainCode"));
//        //判断细维度编码是否存在
//        Set<String> slaveCodes = findExistCodeOrName("slaveCode", excelReader.getQuotaSlaveRepeat().get("slaveCode"));
//
//        TjQuotaMsg model;
//        TjQuotaDMainMsg TjQuotaDMainModel;
//        TjQuotaDSlaveMsg TjQuotaDSlaveModel;
//        boolean valid;
//        for (int i = 0; i < errorLs.size(); i++) {
//            model = errorLs.get(i);
//            TjQuotaDMainModel = quotaMainErrorLs.get(i);
//            TjQuotaDSlaveModel = quotaSlaveErrorLs.get(i);
//            //验证指标编码是否存在
//            if (quotaCodes.contains(model.getCode())) {
//                model.addErrorMsg("code", "该指标编码已存在!");
//            }
//
////            //验证指标名称是否存在
////            if(quotaNames.contains(model.getName())){
////                model.addErrorMsg("name", "该指标名称已存在!");
////            }
//
//            //根据指标类型名称获取指标类型id
//            if (null == quotaTypes.get(model.getQuotaType())) {
//                model.addErrorMsg("quotaType", "该指标类型不存在!");
//            }
//
//            //判断主维度编码是否存在
//            if (mainCodes.contains(TjQuotaDMainModel.getMainCode())) {
//                TjQuotaDMainModel.addErrorMsg("mainCode", "该主维度编码不存在!");
//            }
//
//            //判断细维度编码是否存在
//            if (slaveCodes.contains(TjQuotaDSlaveModel.getSlaveCode())) {
//                TjQuotaDSlaveModel.addErrorMsg("slaveCode", "该细维度编码不存在!");
//            }
//
//            //判断主维度指标编码是否存在(包括库里存在、现导入文件的指标编码)
//            if (!excelReader.getRepeat().get("code").contains(TjQuotaDMainModel.getMainCode())) {
//                TjQuotaDMainModel.addErrorMsg("quotaCode", "导入指标中找不到该主维度的指标编码!");
//            }
//            //判断细维度指标编码是否存在(包括库里存在、现导入文件的指标编码)
//            if (excelReader.getRepeat().get("code").contains(TjQuotaDSlaveModel.getSlaveCode())) {
//                TjQuotaDSlaveModel.addErrorMsg("quotaCode", "导入指标中找不到该细维度的指标编码!");
//            }
//        }
//
//        for (int i = 0; i < correctLs.size(); i++) {
//            valid = true;
//            model = correctLs.get(i);
//            //验证指标编码是否存在
//            if (quotaCodes.contains(model.getCode())) {
//                model.addErrorMsg("code", "该指标编码已存在!");
//                valid = false;
//            }
////            //验证指标名称是否存在
////            if(quotaNames.contains(model.getName())){
////                model.addErrorMsg("name", "该指标名称已存在!");
////                valid = false;
////            }
//
//            //根据指标类型名称获取指标类型id
//            if (null == quotaTypes.get(model.getQuotaType())) {
//                model.addErrorMsg("quotaType", "该指标类型不存在!");
//                valid = false;
//            }
//            //指标错误信息
//            if (!valid) {
//                errorLs.add(model);
//            } else {
//                model.setQuotaType(quotaTypes.get(model.getQuotaType()));
//                model.setCreateUser(user.getId());
//                model.setCreateUserName(user.getRealName());
//            }
//
//            if (valid) {
//                saveLs.add(correctLs.get(i));
//            }
//        }
//        //主维度
//        for (int i = 0; i < quotaMainCorrectLs.size(); i++) {
//            valid = true;
//            TjQuotaDMainModel = quotaMainCorrectLs.get(i);
//
//            //判断主维度编码是否存在
//            if (!(mainCodes.contains(TjQuotaDMainModel.getMainCode()))) {
//                TjQuotaDMainModel.addErrorMsg("mainCode", "该主维度编码不存在!");
//                valid = false;
//            }
//            //判断主维度指标编码是否存在(包括库里存在、现导入文件的指标编码)
//            if (!(quotaCodes.contains(TjQuotaDMainModel.getQuotaCode()) || excelReader.getRepeat().get("code").contains(TjQuotaDMainModel.getQuotaCode()))) {
//                TjQuotaDMainModel.addErrorMsg("quotaCode", "导入的指标中找不到该主维度的指标编码!");
//                valid = false;
//            }
//            //主维度错误信息
//            if (!valid) {
//                quotaMainErrorLs.add(TjQuotaDMainModel);
//            }
//
//            if (valid) {
//                quotaMainLs.add(quotaMainCorrectLs.get(i));
//            }
//        }
//        //细维度
//        for (int i = 0; i < quotaSlaveCorrectLs.size(); i++) {
//            valid = true;
//            TjQuotaDSlaveModel = quotaSlaveCorrectLs.get(i);
//            //判断细维度编码是否存在
//            if (!(slaveCodes.contains(TjQuotaDSlaveModel.getSlaveCode()))) {
//                TjQuotaDSlaveModel.addErrorMsg("slaveCode", "该细维度编码不存在!");
//                valid = false;
//            }
//            //判断细维度指标编码是否存在(包括库里存在、现导入文件的指标编码)
//            if (!(quotaCodes.contains(TjQuotaDSlaveModel.getQuotaCode()) || excelReader.getRepeat().get("code").contains(TjQuotaDSlaveModel.getQuotaCode()))) {
//                TjQuotaDSlaveModel.addErrorMsg("quotaCode", "导入的指标中找不到该细维度的指标编码!");
//                valid = false;
//            }
//            //细维度错误信息
//            if (!valid) {
//                quotaSlaveErrorLs.add(TjQuotaDSlaveModel);
//            }else{
//                quotaSlaveLs.add(quotaSlaveCorrectLs.get(i));
//            }
//        }
//        Map<String, Object> map = new HashMap<>();
//        if (null != saveLs && saveLs.size() > 0) {
//            map.put("saveLs", saveLs);
//            map.put("quotaMainLs", quotaMainLs);
//            map.put("quotaSlaveLs", quotaSlaveLs);
//        }
//        return map;
//    }
//
//    /**
//     * 获取已经存在的指标编码/指标名称
//     *
//     * @param name  检索字段名称
//     * @param codes 检索列表
//     * @return
//     * @throws Exception
//     */
//    private Set<String> findExistCodeOrName(String name, Set<String> codes) throws Exception {
//
//        Map<String, Object> conditionMap = new HashMap<>();
//        String rs = "";
//        //获取存在的主维度
//        if (!StringUtils.isEmpty(name) && name.equals("mainCode")) {
//            if (null != codes && codes.size() > 0) {
//                conditionMap.put("mainCode", toJson(codes));
//                rs = HttpClientUtil.doPost(comUrl + "/quota/TjDimensionMainIsExist", conditionMap);
//            }
//        } else if (!StringUtils.isEmpty(name) && name.equals("slaveCode")) {
//            //获取存在的细维度
//            if (null != codes && codes.size() > 0) {
//                conditionMap.put("slaveCode", toJson(codes));
//                rs = HttpClientUtil.doPost(comUrl + "/quota/TjDimensionSlaveIsExist", conditionMap);
//            }
//        } else {
//            if (null != codes && codes.size() > 0) {
//                conditionMap.put("type", name);
//                conditionMap.put("json", toJson(codes));
//                rs = HttpClientUtil.doPost(comUrl + "/quota/type_isExist", conditionMap);
//            }
//        }
//
//        return objectMapper.readValue(rs, new TypeReference<Set<String>>() {
//        });
//    }
//
//    /**
//     * 根据指标分类的名称获取指标id和name
//     *
//     * @param names 指标分类名称
//     * @return
//     * @throws Exception
//     */
//    private Map<String, String> findExistQuotaType(Set<String> names) throws Exception {
//        Map map = new HashMap<>();
//        String resultStr = "";
//        if (null != names && names.size() > 0) {
//            map.put("name", toJson(names));
//            resultStr = HttpClientUtil.doPost(comUrl + "/quotaCategory/getQuotaCategoryByName", map, username, password);
//        }
//        Envelop envelopAddr = objectMapper.readValue(resultStr, Envelop.class);
//        Map<String, String> quotaCategoryMap = new HashMap<>();
//        if (null != envelopAddr && null != envelopAddr.getObj()) {
//            quotaCategoryMap = objectMapper.readValue(toJson(envelopAddr.getObj()), new TypeReference<Map<String, String>>() {
//            });
//        }
//        return quotaCategoryMap;
//    }
//
//    /**
//     * 指标、数据源、数据存储、主维度、细维度整体入库
//     *
//     * @param lsMap saveLs、quotaMainLs、quotaSlaveLs
//     * @return
//     */
//    private Envelop saveData(Map<String, Object> lsMap) {
//        Envelop ret = new Envelop();
//        Map map = new HashMap<>();
//        try {
//            map.put("lsMap", toJson(lsMap));
//            String envelopStrNew = HttpClientUtil.doPost(comUrl + "/tjQuota/batch", map, username, password);
//            ret = objectMapper.readValue(envelopStrNew,Envelop.class);
//            return ret;
//        } catch (Exception e) {
//            e.printStackTrace();
//            ret.setSuccessFlg(false);
//            ret.setErrorMsg(e.getMessage());
//            return ret;
//        }
//    }
//
//
//    @RequestMapping("/downLoadErrInfo")
//    public void downLoadErrInfo(String f, String datePath, HttpServletResponse response) throws IOException {
//
//        try {
//            f = datePath + TemPath.separator + f;
//            downLoadFile(TemPath.getFullPath(f, parentFile), response);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void downLoadFile(String filePath, HttpServletResponse response) throws IOException {
//
//        InputStream fis = null;
//        OutputStream toClient = null;
//        try {
//            File file = new File(filePath);
//            fis = new BufferedInputStream(new FileInputStream(file));
//            byte[] buffer = new byte[fis.available()];
//            fis.read(buffer);
//            fis.close();
//
//            response.reset();
//            response.setContentType("octets/stream");
//            response.addHeader("Content-Length", "" + file.length());
//            response.addHeader("Content-Disposition", "attachment; filename="
//                    + new String(file.getName().getBytes("gb2312"), "ISO8859-1"));
//
//            toClient = new BufferedOutputStream(response.getOutputStream());
//            toClient.write(buffer);
//            toClient.flush();
//            toClient.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            if (fis != null){
//                fis.close();
//            }
//            if (toClient != null){
//                toClient.close();
//            }
//        }
//    }
//
//    /**
//     * 停止执行指标
//     */
//    @RequestMapping("removeQuota")
//    @ResponseBody
//    public Object removeQuota(Long tjQuotaId) {
//        Envelop envelop = new Envelop();
//        Map<String, Object> params = new HashMap<>();
//        params.put("id", tjQuotaId);
//        try {
//            String url = "/quota/api/v1.0/job/removeJob";
//            String resultStr = HttpClientUtil.doPost(adminInnerUrl + url, params, username, password);
//            if(resultStr.equals("true")){
//                envelop.setSuccessFlg(true);
//            }else{
//                envelop.setSuccessFlg(false);
//            }
//            return envelop;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
//
//}

+ 67 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaDimensionMainController.java

@ -0,0 +1,67 @@
//package com.yihu.jw.basic.agadmin.controller.quota;
//
//import com.yihu.ehr.constants.SessionAttributeKeys;
//
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.util.http.HttpClientUtil;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.SessionAttributes;
//import org.springframework.web.client.RestClientException;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by Administrator on 2017/6/15.
// */
//@RestController
//@RequestMapping("/tjQuotaDimensionMain")
//public class TjQuotaDimensionMainController extends EnvelopRestEndpoint {
//
//
//    /**
//     * 添加主维度子表
//     * @param jsonModel 维度子表信息的json串
//     * @param request
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "addTjQuotaDimensionMain", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Object addTjQuotaDimensionMain(String quotaCode, String jsonModel, HttpServletRequest request) throws IOException {
//        String url = "/tj/addTjQuotaDimensionMain";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        if (!StringUtils.isBlank(quotaCode)) {
//            url = "/tj/deleteMainByQuotaCode";
//            Map<String, Object> params = new HashMap<>();
//            params.put("quotaCode", quotaCode);
//            try {
//                resultStr = HttpClientUtil.doDelete(comUrl + url, params, username, password);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return failed(ERR_SYSTEM_DES);
//            }
//            return resultStr;
//        }
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        params.add("model", jsonModel);
//        RestTemplates templates = new RestTemplates();
//        try {
//            resultStr = templates.doPost(comUrl + url, params);
//        } catch (RestClientException e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return resultStr;
//    }
//}

+ 67 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/quota/TjQuotaDimensionSlaveController.java

@ -0,0 +1,67 @@
//package com.yihu.jw.basic.agadmin.controller.quota;
//
//import com.yihu.ehr.constants.SessionAttributeKeys;
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.util.http.HttpClientUtil;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Controller;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.SessionAttributes;
//import org.springframework.web.client.RestClientException;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by Administrator on 2017/6/15.
// */
//@RestController
//@RequestMapping("/tjQuotaDimensionMain")
//public class TjQuotaDimensionSlaveController extends EnvelopRestEndpoint {
//
//
//    /**
//     * 添加主维度子表
//     * @param jsonModel 维度子表信息的json串
//     * @param request
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping(value = "addTjQuotaDimensionSlave", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Object addTjQuotaDimensionSlave(String quotaCode, String jsonModel, HttpServletRequest request) throws IOException {
//        String url = "/tj/addTjQuotaDimensionSlave";
//        String resultStr = "";
//        Envelop result = new Envelop();
//        if (!StringUtils.isBlank(quotaCode)) {
//            url = "/tj/deleteSlaveByQuotaCode";
//            Map<String, Object> params = new HashMap<>();
//            params.put("quotaCode", quotaCode);
//            try {
//                resultStr = HttpClientUtil.doDelete(comUrl + url, params, username, password);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return failed(ERR_SYSTEM_DES);
//            }
//            return resultStr;
//        }
//        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        params.add("model", jsonModel);
//        RestTemplates templates = new RestTemplates();
//        try {
//            resultStr = templates.doPost(comUrl + url, params);
//        } catch (RestClientException e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//        return resultStr;
//    }
//}

+ 664 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/report/ReportController.java

@ -0,0 +1,664 @@
package com.yihu.jw.basic.agadmin.controller.report;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.report.controller.CalculatePointUtil;
import com.yihu.jw.basic.report.service.QcQuotaResultService;
import com.yihu.jw.entity.ehr.report.QcQuotaResult;
import com.yihu.jw.restmodel.ehr.report.MQcDailyReportQuotaResult;
import com.yihu.jw.restmodel.ehr.report.MQcDailyReportResultDetail;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.LogService;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import io.swagger.annotations.Api;
import jxl.Workbook;
import jxl.format.CellFormat;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.*;
/**
 * Created by llh on 2017/5/9.
 */
@RestController
@RequestMapping("/report")
@Api( tags = {"网关-报表"})
public class ReportController extends EnvelopRestEndpoint {
    @Autowired
    QcQuotaResultService qcQuotaResultService;
    CalculatePointUtil calculatePointUtil=new CalculatePointUtil();
    //所有指标统计结果查询,初始化查询
    @RequestMapping("/getQcOverAllIntegrity")
    public Envelop searchQcOverAllIntegrity(String location,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<QcQuotaResult> newQuotaList = new ArrayList<QcQuotaResult>();
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate = DateUtil.formatYMDToYMDHMS(endTime);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate = calendar.getTime();   //日期往后推一天
        QcQuotaResult qc = null;
        //按区域查询统计结果集
        quotaList = qcQuotaResultService.getQuotaListByLocation(location, startDate, endDate);
        if(null!=quotaList&&quotaList.size() > 0){
            for (int i = 0; i < quotaList.size(); i++) {
                Object[] obj = (Object[]) quotaList.get(i);
                //json处理
                qc = new QcQuotaResult();
                //指标Id
                String quotaId = obj[0].toString();
                qc.setQuotaId(Long.parseLong(quotaId));
                //指标名称
                qc.setQuotaName(obj[1].toString());
                int realNum = 0;
                int totalNum = 0;
                int errorNum = 0;
                int timelyNum = 0;
                String value = "";
                if (obj[2] != null && obj[3] != null && obj[4] != null && obj[5] != null) {
                    //实收数 (数据元的实收为 应收 - 错误数(标识为空的错误code))
                    totalNum = Integer.valueOf(obj[2].toString());
                    qc.setTotalNum(totalNum);
                    //应收数
                    realNum = Integer.valueOf(obj[3].toString());
                    qc.setRealNum(realNum);
                    //错误数量(该字段只针对数据元的准确性统计)
                    errorNum = Integer.valueOf(obj[4].toString());
                    qc.setErrorNum(errorNum);
                    //及时采集的档案数量
                    timelyNum = Integer.valueOf(obj[5].toString());
                    qc.setTimelyNum(timelyNum);
                    value = calculatePointUtil.calculatePoint(quotaId, realNum, totalNum, errorNum, timelyNum);
                }
                qc.setValue(value + "%");
                newQuotaList.add(qc);
            }
        }
        if(newQuotaList.size() > 0){
            result.setDetailModelList(newQuotaList);
            result.setStatus(200);
        }else {
            result.setStatus(200);
            result.setMessage("查询无数据");
            result.setTotalCount(0);
        }
        return result;
    }
    //根据机构查询所有指标统计结果,初始化查询
    @RequestMapping("/getQcOverAllOrgIntegrity")
    public Envelop searchQcOverAllOrgIntegrity(String location,String orgCode,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<QcQuotaResult> newQuotaList = new ArrayList<QcQuotaResult>();
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate =DateUtil.formatYMDToYMDHMS(endTime);
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate=calendar.getTime();   //日期往后推一天
        QcQuotaResult qc=null;
        //按区域查询统计结果集
        quotaList = qcQuotaResultService.getQuotaListByOrgCode(orgCode,startDate,endDate);
        if(null!=quotaList&&quotaList.size() > 0) {
            for (int i = 0; i < quotaList.size(); i++) {
                Object[] obj = (Object[]) quotaList.get(i);
                //json处理
                qc = new QcQuotaResult();
                //指标Id
                String quotaId = obj[2].toString();
                //指标名称
                qc.setQuotaName(obj[3].toString());
                qc.setOrgName(obj[1].toString());
                qc.setOrgCode(obj[0].toString());
                qc.setQuotaId(Long.parseLong(quotaId));
                int realNum = 0;
                int totalNum = 0;
                int errorNum = 0;
                int timelyNum = 0;
                String value = "";
                if (obj[4] != null && obj[5] != null && obj[6] != null && obj[7] != null) {
                    //实收数 (数据元的实收为 应收 - 错误数(标识为空的错误code))
                    totalNum = Integer.valueOf(obj[4].toString());
                    qc.setTotalNum(totalNum);
                    //应收数
                    realNum = Integer.valueOf(obj[5].toString());
                    qc.setRealNum(realNum);
                    //错误数量(该字段只针对数据元的准确性统计)
                    errorNum = Integer.valueOf(obj[6].toString());
                    qc.setErrorNum(errorNum);
                    //及时采集的档案数量
                    timelyNum = Integer.valueOf(obj[7].toString());
                    qc.setTimelyNum(timelyNum);
                    value = calculatePointUtil.calculatePoint(quotaId, realNum, totalNum, errorNum, timelyNum);
                }
                qc.setValue(value + "%");
                newQuotaList.add(qc);
            }
        }
        if(newQuotaList.size() > 0){
            result.setDetailModelList(newQuotaList);
            result.setStatus(200);
        }else {
            result.setStatus(200);
            result.setMessage("查询无数据");
            result.setTotalCount(0);
            result.setDetailModelList(newQuotaList);
        }
        return result;
    }
    //趋势分析 - 按区域列表查询,初始化查询
    @RequestMapping("/getQcQuotaIntegrity")
    public Envelop searchQcQuotaIntegrity(String location,String quotaId,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<MQcDailyReportQuotaResult> newQuotaList = new ArrayList<MQcDailyReportQuotaResult>();
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate =DateUtil.formatYMDToYMDHMS(endTime);
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate=calendar.getTime();   //日期往后推一天
        MQcDailyReportQuotaResult qc=null;
        if(!StringUtils.isEmpty(quotaId)){
            //区域整体统计结果 - 按机构及指标划分
            quotaList = qcQuotaResultService.getQuotaListByLocation(location,Long.parseLong(quotaId),startDate, endDate);
            if(null!=quotaList&&quotaList.size() > 0){
                for(int i=0;i<quotaList.size();i++){
                    Object[] obj = (Object[])quotaList.get(i);
                    //json处理
                    qc=new MQcDailyReportQuotaResult();
                    String quotaIdstr = obj[0].toString();
                    //指标名称
                    qc.setQuotaName(obj[1].toString());
                    String eventTime=obj[2].toString();
                    if(null!=eventTime&&!"".equals(eventTime)){
                        //事件时间
                        qc.setEventTime(eventTime.substring(0,4)+"年"+eventTime.substring(5,7)+"月"+eventTime.substring(8,10)+"日");
                    }
                    int realNum = 0;
                    int totalNum = 0;
                    int errorNum = 0;
                    int timelyNum = 0;
                    String value="";
                    if(obj[3] != null && obj[4] != null && obj[5] != null && obj[6] != null){
                        //实收数 (数据元的实收为 应收 - 错误数(标识为空的错误code))
                        totalNum = Integer.valueOf(obj[3].toString());
                        qc.setTotalNum(totalNum);
                        //应收数
                        realNum = Integer.valueOf(obj[4].toString());
                        qc.setRealNum(realNum);
                        //错误数量(该字段只针对数据元的准确性统计)
                        errorNum = Integer.valueOf(obj[5].toString());
                        qc.setErrorNum(errorNum);
                        //及时采集的档案数量
                        timelyNum = Integer.valueOf(obj[6].toString());
                        qc.setTimelyNum(timelyNum);
                        value=calculatePointUtil.calculatePoint(quotaIdstr, realNum, totalNum , errorNum , timelyNum);
                    }
                    DecimalFormat df = new DecimalFormat("0.00");
                    if(obj[0] != null){
                        //指标ID
                        qc.setQuotaId( Long.valueOf(obj[0].toString()));
                    }
                    qc.setValue(value+"%");
                    String an=obj[7].toString();
                    if(null!=an&&an.length()>5){
                        qc.setAn(an.substring(0,6)+'%');
                    }else{
                        qc.setAn(an+'%');
                    }
                    String mom=obj[8].toString();
                    if(null!=mom&&mom.length()>5){
                        qc.setMom(mom.substring(0,6)+'%');
                    }else{
                        qc.setMom(mom+'%');
                    }
                    newQuotaList.add(qc);
                }
                result.setDetailModelList(newQuotaList);
                result.setStatus(200);
            }else {
                result.setStatus(200);
                result.setMessage("查询无数据");
                result.setTotalCount(0);
            }
        }
        return result;
    }
    //趋势分析 -按机构列表查询,初始化查询
    @RequestMapping("/getQcQuotaOrgIntegrity")
    public Envelop searchQcQuotaOrgIntegrity(String orgCode,String quotaId,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<MQcDailyReportQuotaResult> newQuotaList = new ArrayList<MQcDailyReportQuotaResult>();
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate =DateUtil.formatYMDToYMDHMS(endTime);
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate=calendar.getTime();   //日期往后推一天
        MQcDailyReportQuotaResult qc = null;
        if(!StringUtils.isEmpty(quotaId)){
            quotaList = qcQuotaResultService.getQuotaListByOrg(orgCode, Long.parseLong(quotaId), startDate, endDate);
            if (null!=quotaList&&quotaList.size() > 0) {
                for (int i = 0; i < quotaList.size(); i++) {
                    Object[] obj = (Object[]) quotaList.get(i);
                    //json处理
                    qc = new MQcDailyReportQuotaResult();
                    String quotaIdstr = obj[0].toString();
                    //指标名称
                    qc.setQuotaName(obj[1].toString());
                    String eventTime=obj[2].toString();
                    if(null!=eventTime&&!"".equals(eventTime)){
                        //事件时间
                        qc.setEventTime(eventTime.substring(0,4)+"年"+eventTime.substring(5,7)+"月"+eventTime.substring(8,10)+"日");
                    }
                    int realNum = 0;
                    int totalNum = 0;
                    int errorNum = 0;
                    int timelyNum = 0;
                    String value="";
                    if (obj[3] != null && obj[4] != null && obj[5] != null && obj[6] != null) {
                        //实收数 (数据元的实收为 应收 - 错误数(标识为空的错误code))
                        totalNum = Integer.valueOf(obj[3].toString());
                        qc.setTotalNum(totalNum);
                        //应收数
                        realNum = Integer.valueOf(obj[4].toString());
                        qc.setRealNum(realNum);
                        //错误数量(该字段只针对数据元的准确性统计)
                        errorNum = Integer.valueOf(obj[5].toString());
                        qc.setErrorNum(errorNum);
                        //及时采集的档案数量
                        timelyNum = Integer.valueOf(obj[6].toString());
                        qc.setTimelyNum(timelyNum);
                        value=calculatePointUtil.calculatePoint(quotaIdstr, realNum, totalNum , errorNum , timelyNum);
                    }
                    DecimalFormat df = new DecimalFormat("0.00");
                    if (obj[0] != null) {
                        //指标ID
                        qc.setQuotaId( Long.valueOf(obj[0].toString()));
                    }
                    qc.setValue(value+ "%");
                    String an=obj[7].toString();
                    if(null!=an&&an.length()>5){
                        qc.setAn(an.substring(0,6)+'%');
                    }else{
                        qc.setAn(an+'%');
                    }
                    String mom=obj[8].toString();
                    if(null!=mom&&mom.length()>5){
                        qc.setMom(mom.substring(0,6)+'%');
                    }else{
                        qc.setMom(mom+'%');
                    }
                    newQuotaList.add(qc);
                }
                result.setDetailModelList(newQuotaList);
                result.setStatus(200);
            } else {
                result.setStatus(200);
                result.setMessage("查询无数据");
                result.setTotalCount(0);
            }
        }
        return result;
    }
    //分析明细列表
    @RequestMapping("/getQcQuotaDailyIntegrity")
    public Envelop searchQcQuotaDailyIntegrity(String location,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<Object> detailQuotaList = new ArrayList<Object>();
//        int firstDate=(page-1)*size;
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate = DateUtil.formatYMDToYMDHMS(endTime);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate = calendar.getTime();   //日期往后推一天
        Map<String, String> QcQuotaResultAnalyseMap = new TreeMap();
        //获取区域名称和事件时间
        quotaList = qcQuotaResultService.getfindQcListByLocationAndTime(location, startDate, endDate);
        if (null!=quotaList&&quotaList.size() > 0) {
            for (int i = 0; i < quotaList.size(); i++) {
                Object[] obj = (Object[]) quotaList.get(i);
                String eventTime = obj[2].toString();
                String newEventTime = "";
                if (null != eventTime && !"".equals(eventTime)) {
                    //事件时间
                    newEventTime = eventTime.substring(0,4)+"年"+eventTime.substring(5,7)+"月"+eventTime.substring(8,10)+"日";
                }
                String qcKey = obj[2].toString().substring(0, 10) + obj[3].toString();
                QcQuotaResultAnalyseMap.put(qcKey, newEventTime);
            }
        }
        //区域整体统计结果
        detailQuotaList = qcQuotaResultService.getQuotaListByLocationAndTime(location, startDate, endDate);
        Map<String, MQcDailyReportResultDetail> detailMap = new TreeMap();
        Map<String, MQcDailyReportResultDetail> detailAnMap = new TreeMap();
        Map<String, MQcDailyReportResultDetail> detailMonMap = new TreeMap();
        MQcDailyReportResultDetail qrd = null;
        if(null!=detailQuotaList&&detailQuotaList.size() > 0){
            for (int i = 0; i < detailQuotaList.size(); i++) {
                Object[] obj = (Object[]) detailQuotaList.get(i);
                String qcKey = obj[0].toString().substring(0, 10) + obj[2].toString();
                if (null != QcQuotaResultAnalyseMap.get(qcKey)) {
                    String resultQuotaId = obj[3].toString();
                    //总比
                    String detailMapKey = qcKey + "总比";
                    Map<String, String> map = calculatePointUtil.reportDetailData("1", obj);
                    //,map.get("1standard")
                    detailMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailMap, detailMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "总比", map.get("1"),map.get("1standard"));
                    //同比
                    String detailAnMapKey = qcKey + "同比";
                    map = calculatePointUtil.reportDetailData("2", obj);
                    detailAnMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailAnMap, detailAnMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "同比", map.get("2"),"");
                    //环比
                    String detailMonMapKey = qcKey + "环比";
                    map = calculatePointUtil.reportDetailData("3", obj);
                    detailMonMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailMonMap, detailMonMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "环比", map.get("3"),"");
                }
            }
        }
        List<MQcDailyReportResultDetail>  objectList=new ArrayList<MQcDailyReportResultDetail>();
        for (String key : detailMap.keySet()) {
            String mapKey=key.substring(0,key.length()-2);
            objectList.add(detailMap.get(key));
            objectList.add(detailAnMap.get(mapKey+"同比"));
            objectList.add(detailMonMap.get(mapKey+"环比"));
        }
        if(objectList.size() > 0){
            result.setDetailModelList(objectList);
            result.setStatus(200);
        }else {
            result.setStatus(200);
            result.setMessage("查询无数据");
            result.setTotalCount(0);
        }
        return result;
    }
    //根据地区、期间查询各机构某项指标的值
    @RequestMapping("/getQcQuotaByLocation")
    public Envelop searchQcQuotaByLocation(String location,String quotaId,String startTime,String endTime){
        PageEnvelop result = new PageEnvelop();
        List<Object> quotaList = new ArrayList<Object>();
        List<QcQuotaResult> newQuotaList = new ArrayList<QcQuotaResult>();
        Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
        Date endDate =DateUtil.formatYMDToYMDHMS(endTime);
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(endDate);
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        endDate=calendar.getTime();   //日期往后推一天
        QcQuotaResult qc=null;
        if(!StringUtils.isEmpty(quotaId)){
            //区域整体统计结果 - 按机构及指标划分
            //@Query("select qc.orgCode,qc.orgName,qc.quotaId,qc.quotaName,sum(qc.totalNum) as totalNum,sum(qc.realNum) as realNum,sum(qc.errorNum) as errorNum,sum(qc.timelyNum) as timelyNum
            quotaList = qcQuotaResultService.getQuotaListByLocationGBOrg(location,Long.parseLong(quotaId),startDate, endDate);
            if(null!=quotaList&&quotaList.size() > 0){
                for(int i=0;i<quotaList.size();i++){
                    Object[] obj = (Object[])quotaList.get(i);
                    //json处理
                    qc=new QcQuotaResult();
                    qc.setOrgCode(obj[0].toString());
                    qc.setOrgName(obj[1].toString());
                    String quotaIdstr = obj[2].toString();
                    //指标名称
                    qc.setQuotaName(obj[3].toString());
                    int realNum = 0;
                    int totalNum = 0;
                    int errorNum = 0;
                    int timelyNum = 0;
                    String value="";
                    if(obj[4] != null && obj[5] != null && obj[6] != null && obj[7] != null){
                        //实收数 (数据元的实收为 应收 - 错误数(标识为空的错误code))
                        totalNum = Integer.valueOf(obj[4].toString());
                        qc.setTotalNum(totalNum);
                        //应收数
                        realNum = Integer.valueOf(obj[5].toString());
                        qc.setRealNum(realNum);
                        //错误数量(该字段只针对数据元的准确性统计)
                        errorNum = Integer.valueOf(obj[6].toString());
                        qc.setErrorNum(errorNum);
                        //及时采集的档案数量
                        timelyNum = Integer.valueOf(obj[7].toString());
                        qc.setTimelyNum(timelyNum);
                        value=calculatePointUtil.calculatePoint(quotaIdstr, realNum, totalNum , errorNum , timelyNum);
                    }
                    DecimalFormat df = new DecimalFormat("0.00");
                    if(obj[2] != null){
                        //指标ID
                        qc.setQuotaId( Long.valueOf(obj[2].toString()));
                    }
                    qc.setValue(value+"%");
                    newQuotaList.add(qc);
                }
                result.setDetailModelList(newQuotaList);
                result.setStatus(200);
            }else {
                result.setStatus(200);
                result.setMessage("查询无数据");
                result.setTotalCount(0);
            }
        }
        return result;
    }
    //根据地区、期间查询分析明细列表,并导出
    @RequestMapping("/exportToExcel")
    public void exportToExcel(HttpServletResponse response,String location,String startTime,String endTime){
        try {
            String fileName = "分析列表明细";
            String url="";
            String envelopStr = "";
            //设置下载
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" )+".xls");
            OutputStream os = response.getOutputStream();
            //获取导出字典
            Map<String,Object> params = new HashMap<>();
            url = "/report/getQcQuotaDailyIntegrity";
            params.put("location",location);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            List<Object> quotaList = new ArrayList<Object>();
            List<Object> detailQuotaList = new ArrayList<Object>();
//        int firstDate=(page-1)*size;
            Date startDate = DateUtil.formatYMDToYMDHMS(startTime);
            Date endDate = DateUtil.formatYMDToYMDHMS(endTime);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
            endDate = calendar.getTime();   //日期往后推一天
            Map<String, String> QcQuotaResultAnalyseMap = new TreeMap();
            //获取区域名称和事件时间
            quotaList = qcQuotaResultService.getfindQcListByLocationAndTime(location, startDate, endDate);
            if (null!=quotaList&&quotaList.size() > 0) {
                for (int i = 0; i < quotaList.size(); i++) {
                    Object[] obj = (Object[]) quotaList.get(i);
                    String eventTime = obj[2].toString();
                    String newEventTime = "";
                    if (null != eventTime && !"".equals(eventTime)) {
                        //事件时间
                        newEventTime = eventTime.substring(0,4)+"年"+eventTime.substring(5,7)+"月"+eventTime.substring(8,10)+"日";
                    }
                    String qcKey = obj[2].toString().substring(0, 10) + obj[3].toString();
                    QcQuotaResultAnalyseMap.put(qcKey, newEventTime);
                }
            }
            //区域整体统计结果
            detailQuotaList = qcQuotaResultService.getQuotaListByLocationAndTime(location, startDate, endDate);
            Map<String, MQcDailyReportResultDetail> detailMap = new TreeMap();
            Map<String, MQcDailyReportResultDetail> detailAnMap = new TreeMap();
            Map<String, MQcDailyReportResultDetail> detailMonMap = new TreeMap();
            MQcDailyReportResultDetail qrd = null;
            if(null!=detailQuotaList&&detailQuotaList.size() > 0){
                for (int i = 0; i < detailQuotaList.size(); i++) {
                    Object[] obj = (Object[]) detailQuotaList.get(i);
                    String qcKey = obj[0].toString().substring(0, 10) + obj[2].toString();
                    if (null != QcQuotaResultAnalyseMap.get(qcKey)) {
                        String resultQuotaId = obj[3].toString();
                        //总比
                        String detailMapKey = qcKey + "总比";
                        Map<String, String> map = calculatePointUtil.reportDetailData("1", obj);
                        //,map.get("1standard")
                        detailMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailMap, detailMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "总比", map.get("1"),map.get("1standard"));
                        //同比
                        String detailAnMapKey = qcKey + "同比";
                        map = calculatePointUtil.reportDetailData("2", obj);
                        detailAnMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailAnMap, detailAnMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "同比", map.get("2"),"");
                        //环比
                        String detailMonMapKey = qcKey + "环比";
                        map = calculatePointUtil.reportDetailData("3", obj);
                        detailMonMap = calculatePointUtil.detailValueModel(resultQuotaId, i, detailMonMap, detailMonMapKey, QcQuotaResultAnalyseMap.get(qcKey), obj[2].toString(), obj[1].toString(), "环比", map.get("3"),"");
                    }
                }
            }
            List<MQcDailyReportResultDetail>  qcModelList=new ArrayList<MQcDailyReportResultDetail>();
            for (String key : detailMap.keySet()) {
                String mapKey=key.substring(0,key.length()-2);
                qcModelList.add(detailMap.get(key));
                qcModelList.add(detailAnMap.get(mapKey+"同比"));
                qcModelList.add(detailMonMap.get(mapKey+"环比"));
            }
            //写excel
            WritableWorkbook wwb = Workbook.createWorkbook(os);
            //创建Excel工作表 指定名称和位置
            WritableSheet ws = wwb.createSheet("质控分析明细",0);
            addStaticCell(ws);//添加固定信息,题头等
            //添加字典项信息
            WritableCellFormat wc = new WritableCellFormat();
            wc.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, Colour.SKY_BLUE);//边框
            MQcDailyReportResultDetail qc=null;
            for(int i=0;i<qcModelList.size();i++) {
                int j=i+1;
                qc = qcModelList.get(i);
                //添加列表明细
                addCell(ws,0,j,qc.getEventTime(),wc);//时间
                addCell(ws,1,j,qc.getOrgName(),wc);//机构名称
                addCell(ws,2,j,qc.getScaleType(),wc);//比例名称
                addCell(ws,3,j,qc.getArIntegrity(),wc);//整体数量完整性
                addCell(ws,4,j,qc.getDsIntegrity(),wc);//数据集完整性
                addCell(ws,5,j,qc.getMdIntegrity(),wc);//数据元完整性
                addCell(ws,6,j,qc.getMdAccuracy(),wc);//准确性
                addCell(ws,7,j,qc.getArTimely(),wc);//全部及时性
                addCell(ws,8,j,qc.getHpTimely(),wc);//住院病人及时性
                addCell(ws,9,j,qc.getOpTimely(),wc);//门诊病人及时性
            }
            //写入工作表
            wwb.write();
            wwb.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //excel中添加固定内容
    private void addStaticCell(WritableSheet ws){
        try {
            addCell(ws,0,0,"时间");
            addCell(ws,1,0,"对象");
            addCell(ws,2,0," ");
            addCell(ws,3,0,"整体数量完整性");
            addCell(ws,4,0,"数据集完整性");
            addCell(ws,5,0,"数据元完整性");
            addCell(ws,6,0,"准确性");
            addCell(ws,7,0,"全部及时性");
            addCell(ws,8,0,"住院病人及时性");
            addCell(ws,9,0,"门诊病人及时性");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //添加单元格内容
    private void addCell(WritableSheet ws,int column,int row,String data){
        try {
            Label label = new Label(column,row,data);
            ws.addCell(label);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //添加单元格内容带样式
    private void addCell(WritableSheet ws,int column,int row,String data,CellFormat cellFormat){
        try {
            Label label = new Label(column,row,data,cellFormat);
            ws.addCell(label);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 档案入库状况数据
     * @param model
     * @return
     */
//    @RequestMapping("rukuData")
//    public Object rukuData(Model model,String orgCode,String startDate,String endDate) {
//        String url = "/report/qcDailyStatisticsStorageByDate";
//        String resultStr = "";
//        Map<String, Object> params = new HashMap<>();
//        Envelop result = new Envelop();
//        try {
//            params.put("orgCode",orgCode);
//            params.put("startDate",startDate);
//            params.put("endDate",endDate);
//            resultStr = HttpClientUtil.doGet(comUrl + url, params, username, password);
//            ObjectMapper mapper = new ObjectMapper();
//            Envelop envelop = mapper.readValue(resultStr, Envelop.class);
//            if (!envelop.isSuccessFlg()) {
//                result.setSuccessFlg(true);
//                result.setDetailModelList(envelop.getDetailModelList());
//                result.setObj(envelop.getObj());
//                return result;
//            } else {
//                result.setSuccessFlg(false);
//                return result;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failed(ERR_SYSTEM_DES);
//        }
//    }
}

+ 127 - 171
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceBrowseController.java

@ -1,49 +1,56 @@
//package com.yihu.jw.basic.agadmin.controller.resource;
//
//
//import com.yihu.jw.restmodel.ehr.resource.MRsColumnsModel;
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.util.http.HttpClientUtil;
//import com.yihu.jw.util.network.HttpResponse;
//import com.yihu.jw.util.network.HttpUtils;
//import jxl.Cell;
//import jxl.Workbook;
//import jxl.write.Label;
//import jxl.write.WritableSheet;
//import jxl.write.WritableWorkbook;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.ui.Model;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.OutputStream;
//import java.util.*;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//
///**
// * 资源浏览服务控制器
// * Created by wq on 2016/5/17.
// */
//@RestController
//@RequestMapping("/resourceBrowse")
//public class ResourceBrowseController extends EnvelopRestEndpoint {
//
//    private static final Logger logger = LoggerFactory.getLogger(ResourceBrowseController.class);
//    private static final Integer SINGLE_REQUEST_SIZE = 5000; //导出Excel时的单次请求量
//    private static final Integer SINGLE_EXCEL_SIZE = 50000; //导出Excel时的单个文件数据量
//
//
//
package com.yihu.jw.basic.agadmin.controller.resource;
import com.yihu.jw.basic.agadmin.service.ResourceBrowseControllerService;
import com.yihu.jw.restmodel.ehr.resource.MRsColumnsModel;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.network.HttpResponse;
import com.yihu.jw.util.network.HttpUtils;
import io.swagger.annotations.Api;
import jxl.Cell;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 资源浏览服务控制器
 * Created by wq on 2016/5/17.
 */
@RestController
@RequestMapping("/resourceBrowse")
@Api( tags = {"网关-资源浏览"})
public class ResourceBrowseController extends EnvelopRestEndpoint {
    private static final Logger logger = LoggerFactory.getLogger(ResourceBrowseController.class);
    private static final Integer SINGLE_REQUEST_SIZE = 5000; //导出Excel时的单次请求量
    private static final Integer SINGLE_EXCEL_SIZE = 50000; //导出Excel时的单个文件数据量
    @Autowired
    ResourceBrowseControllerService resourceBrowseControllerService;
    @Autowired
    private ResourceIntegratedController resourceIntegratedController;
//    @RequestMapping("/searchResourceList")
//    @ResponseBody
//    public Object searchResourceList() throws Exception {
//        Map<String, Object> params = new HashMap<>();
//        String url = "/resources/categories/all";
@ -94,8 +101,6 @@
//    public  List<MRsColumnsModel> getColumns(String resourceCode, HttpServletRequest request) throws Exception {
//        List<MRsColumnsModel> result = new ArrayList<>();
//        //从Session中获取用户的角色信息作为查询参数
//        boolean isAccessAll = getIsAccessAllRedis(request);
//        List<String> userRoleList  = getUserRolesListRedis(request);
//        // 获取资源拥着信息
//        String urlGet = "/resource/api/v1.0/resources/byCode";
//        Map<String, Object> getParams = new HashMap<>();
@ -109,11 +114,7 @@
//        Map<String, Object> params = new HashMap<>();
//        String userId = String.valueOf(request.getSession().getAttribute("userId"));
//        String creator = String.valueOf(rsObj.get("creator"));
//        if (isAccessAll || userId.equals(creator)) {
//            params.put("roleId", "*");
//        } else {
//            params.put("roleId", objectMapper.writeValueAsString(userRoleList));
//        }
//        params.put("roleId", "*");
//        params.put("resourcesCode", resourceCode);
//        response = HttpUtils.doGet(adminInnerUrl + url, params);
//        return toModel(response.getContent(), List.class);
@ -138,123 +139,78 @@
//        }
//        return envelop;
//    }
//
//    /**
//     * 档案资源浏览
//     * @param resourcesCode
//     * @param searchParams
//     * @param page
//     * @param rows
//     * @param request
//     * @return
//     */
//    @RequestMapping("/searchResourceData")
//    @ResponseBody
//    public Object searchResourceData(String resourcesCode, String searchParams, int page, int rows, HttpServletRequest request) throws Exception {
//        Envelop envelop = new Envelop();
//        String url = "/resources/ResourceBrowses/getResourceData";
//        //从Session中获取用户的角色信息和授权视图列表作为查询参数
//        List<String> userRolesList  = getUserRolesListRedis(request);
//        List<String> userOrgSaasList  = getUserOrgSaasListRedis(request);
//        List<String> userAreaSaasList  = getUserAreaSaasListRedis(request);
//        boolean isAccessAll = getIsAccessAllRedis(request);
//        if (!isAccessAll) {
//            if ((null == userOrgSaasList || userOrgSaasList.size() <= 0) && (null == userAreaSaasList || userAreaSaasList.size() <= 0)) {
//                envelop.setSuccessFlg(false);
//                envelop.setErrorMsg("无权访问");
//                return envelop;
//            }
//        }
//        Map<String, Object> params = new HashMap<>();
//        params.put("resourcesCode", resourcesCode);
//        if (isAccessAll) {
//            params.put("roleId", "*");
//            params.put("orgCode", "*");
//            params.put("areaCode", "*");
//        } else {
//            // 获取资源拥着信息
//            String urlGet = "/resources/byCode";
//            Map<String, Object> getParams = new HashMap<>();
//            getParams.put("code", resourcesCode);
//            String result1 = HttpClientUtil.doGet(comUrl + urlGet, getParams, username, password);
//            Envelop getEnvelop = objectMapper.readValue(result1, Envelop.class);
//            if (!getEnvelop.isSuccessFlg()) {
//                envelop.setSuccessFlg(false);
//                envelop.setErrorMsg("原资源信息获取失败!");
//                return envelop;
//            }
//            Map<String, Object> rsObj = (Map<String, Object>) getEnvelop.getObj();
//            String userId = String.valueOf(request.getSession().getAttribute("userId"));
//            String creator = String.valueOf(rsObj.get("creator"));
//            // 判断视图是否由用户生成
//            if (userId.equals(creator)) {
//                params.put("roleId", "*");
//            } else {
//                params.put("roleId", objectMapper.writeValueAsString(userRolesList));
//            }
//            params.put("orgCode", objectMapper.writeValueAsString(userOrgSaasList));
//            params.put("areaCode", objectMapper.writeValueAsString(userAreaSaasList));
//        }
//        Pattern pattern = Pattern.compile("\\[.+?\\]");
//        Matcher matcher = pattern.matcher(searchParams);
//        if (matcher.find()) {
//            if (searchParams.contains("{") || searchParams.contains("}")) {
//                params.put("queryCondition", searchParams);
//            } else {
//                params.put("queryCondition", "");
//            }
//        } else {
//            params.put("queryCondition", "");
//        }
//        params.put("page", page);
//        params.put("size", rows);
//        HttpResponse response = HttpUtils.doGet(comUrl + url, params);
//        if (response.isSuccessFlg()) {
//            envelop = toModel(response.getContent(), Envelop.class);
//            if (envelop.isSuccessFlg()) {
//                List<Map<String, Object>> envelopList = envelop.getDetailModelList();
//                List<Map<String, Object>> middleList = new ArrayList<>();
//                for (Map<String, Object> envelopMap : envelopList) {
//                    Map<String, Object> resultMap = new HashMap<String, Object>();
//                    for (String key : envelopMap.keySet()) {
//                        String value = envelopMap.get(key) == null? "" : String.valueOf(envelopMap.get(key));
//                        if (key.equals("event_type")) {
//                            String eventType = envelopMap.get(key).toString();
//                            if (eventType.equals("0")) {
//                                resultMap.put(key, "门诊");
//                            } else if (eventType.equals("1")) {
//                                resultMap.put(key, "住院");
//                            } else if (eventType.equals("2")) {
//                                resultMap.put(key, "体检");
//                            } else {
//                                resultMap.put(key, "未知");
//                            }
//                        } else if (value.contains("T") && value.contains("Z")) {
//                            String newDateStr = value.replace("T", " ").replace("Z", "");
//                            resultMap.put(key, newDateStr);
//                        } else {
//                            resultMap.put(key, value);
//                        }
//                    }
//                    middleList.add(resultMap);
//                }
//                List<Map<String, Object>> finalList = resourceIntegratedController.changeIdCardNo(middleList, request);
//                envelop.setDetailModelList(finalList);
//                envelop.setSuccessFlg(true);
//                return envelop;
//            } else {
//                return envelop;
//            }
//        }
//        return toModel(response.getContent(), Envelop.class);
//    }
//
//    /**
//     * 档案资源浏览细表数据 zuul
//     * @param rowKey
//     * @param version
//     * @return
//     */
    /**
     * 档案资源浏览
     * @param resourcesCode
     * @param searchParams
     * @param page
     * @param rows
     * @param request
     * @return
     */
    @GetMapping("/searchResourceData")
    public Envelop searchResourceData(String resourcesCode, String searchParams, int page, int rows, HttpServletRequest request) throws Exception {
        String url = "/resources/ResourceBrowses/getResourceData";
        Map<String, Object> params = new HashMap<>();
        params.put("resourcesCode", resourcesCode);
        params.put("roleId", "*");
        params.put("orgCode", "*");
        params.put("areaCode", "*");
        String queryCondition = "";
        if(!StringUtils.isEmpty(searchParams)){
            Pattern pattern = Pattern.compile("\\[.+?\\]");
            Matcher matcher = pattern.matcher(searchParams);
            if (matcher.find()) {
                if (searchParams.contains("{") || searchParams.contains("}")) {
                    queryCondition = searchParams;
                }
            }
        }
        Envelop envelop = resourceBrowseControllerService.getResourceData(resourcesCode,"*","*","*",queryCondition,page,rows,null);
        if (envelop.getStatus()==200) {
            ListEnvelop listEnvelop = (ListEnvelop) envelop;
            List<Map<String, Object>> envelopList = listEnvelop.getDetailModelList();
            List<Map<String, Object>> middleList = new ArrayList<>();
            for (Map<String, Object> envelopMap : envelopList) {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                for (String key : envelopMap.keySet()) {
                    String value = envelopMap.get(key) == null? "" : String.valueOf(envelopMap.get(key));
                    if (key.equals("event_type")) {
                        String eventType = envelopMap.get(key).toString();
                        if (eventType.equals("0")) {
                            resultMap.put(key, "门诊");
                        } else if (eventType.equals("1")) {
                            resultMap.put(key, "住院");
                        } else if (eventType.equals("2")) {
                            resultMap.put(key, "体检");
                        } else {
                            resultMap.put(key, "未知");
                        }
                    } else if (value.contains("T") && value.contains("Z")) {
                        String newDateStr = value.replace("T", " ").replace("Z", "");
                        resultMap.put(key, newDateStr);
                    } else {
                        resultMap.put(key, value);
                    }
                }
                middleList.add(resultMap);
            }
            List<Map<String, Object>> finalList = resourceIntegratedController.changeIdCardNo(middleList, request);
            return ListEnvelop.getSuccess("查询成功",finalList);
        }
        return envelop;
    }
    /**
     * 档案资源浏览细表数据 zuul
     * @param rowKey
     * @param version
     * @return
     */
//    @RequestMapping("/searchResourceSubData")
//    @ResponseBody
//    public Object getRsDictEntryList(String rowKey, String version) throws Exception {
@ -681,5 +637,5 @@
//        }
//        return value;
//    }
//
//}
}

+ 4 - 1
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceDefaultParamController.java

@ -3,6 +3,7 @@ package com.yihu.jw.basic.agadmin.controller.resource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.basic.resource.dao.RsResourceDefaultParamDao;
import com.yihu.jw.basic.resource.service.RsResourceDefaultParamService;
import com.yihu.jw.entity.ehr.resource.RsResourceDefaultParam;
import com.yihu.jw.restmodel.web.Envelop;
@ -32,6 +33,8 @@ public class ResourceDefaultParamController extends EnvelopRestEndpoint {
    @Autowired
    private RsResourceDefaultParamService resourceDefaultParamService;
    @Autowired
    private RsResourceDefaultParamDao resourceDefaultParamDao;
    @RequestMapping("/infoInitial")
    public Envelop rsDefaultParamInfoInitial(String id,String resourcesId,String resourcesCode,String mode,String rowIndex){
@ -93,7 +96,7 @@ public class ResourceDefaultParamController extends EnvelopRestEndpoint {
            if(id == null){
                return failed("id不能为空!");
            }
            resourceDefaultParamService.delete(id);
            resourceDefaultParamDao.deleteById(id);
            return success();
        }catch (Exception ex){
            ex.printStackTrace();

+ 9 - 12
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceInterfaceController.java

@ -1,7 +1,6 @@
package com.yihu.jw.basic.agadmin.controller.resource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.resource.dao.RsInterfaceDao;
import com.yihu.jw.basic.resource.service.RsInterfaceService;
import com.yihu.jw.entity.ehr.id.BizObject;
import com.yihu.jw.entity.ehr.resource.RsInterface;
@ -9,14 +8,10 @@ import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.LogService;
import com.yihu.jw.util.http.HttpClientUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@ -27,12 +22,14 @@ import java.util.Map;
 * Created by yww on 2016/5/24.
 */
@RestController
@Api( tags = {"网关-资源接口"})
@RequestMapping("/resource/resourceInterface")
public class ResourceInterfaceController extends EnvelopRestEndpoint {
    @Autowired
    private RsInterfaceService interfaceService;
    @Autowired
    private RsInterfaceDao rsInterfaceDao;
    @RequestMapping("/infoInitial")
    public Envelop resourceInterfaceInfoInitial(String id,String mode){
@ -40,7 +37,7 @@ public class ResourceInterfaceController extends EnvelopRestEndpoint {
        String envelopStr = "";
        try{
            if (!StringUtils.isEmpty(id)) {
                RsInterface rsInterface = interfaceService.retrieve(id);
                RsInterface rsInterface = interfaceService.getOne(id);
                return ObjEnvelop.getSuccess("查询成功",rsInterface);
            }
            return success();
@ -71,7 +68,7 @@ public class ResourceInterfaceController extends EnvelopRestEndpoint {
    public Envelop getResourceInterface(String id){
        Envelop envelop = new Envelop();
        try{
            RsInterface rsInterface = interfaceService.retrieve(id);
            RsInterface rsInterface = interfaceService.getOne(id);
            return ObjEnvelop.getSuccess("查询成功",rsInterface);
        } catch (Exception ex){
            ex.printStackTrace();
@ -108,7 +105,7 @@ public class ResourceInterfaceController extends EnvelopRestEndpoint {
                interfaceService.save(rsInterface);
                return ObjEnvelop.getSuccess("新增成功",rsInterface);
            } else if("modify".equals(mode)){
                RsInterface updateModel = interfaceService.retrieve(rsInterface.getId());
                RsInterface updateModel = interfaceService.getOne(rsInterface.getId());
                if (updateModel==null){
                    return failed("原资源接口信息获取失败");
                }
@ -132,7 +129,7 @@ public class ResourceInterfaceController extends EnvelopRestEndpoint {
    public Envelop deleteRsInterface(String id){
        Envelop envelop = new Envelop();
        try{
            interfaceService.delete(id);
            rsInterfaceDao.deleteById(id);
            return success();
        } catch(Exception ex){
            ex.printStackTrace();

+ 4 - 2
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/RsResourceCategoryController.java

@ -11,6 +11,7 @@ import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.http.HttpClientUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -33,6 +34,7 @@ import java.util.Map;
 */
@RequestMapping("/rscategory")
@RestController
@Api( tags = {"网关-资源分类"})
public class RsResourceCategoryController extends EnvelopRestEndpoint {
    @Autowired
@ -215,7 +217,7 @@ public class RsResourceCategoryController extends EnvelopRestEndpoint {
     * @return
     */
    @RequestMapping("/getCateTypeById")
    public Envelop getCdaTypeById(String strIds) {
    public ObjEnvelop getCdaTypeById(String strIds) {
        Envelop envelop = new Envelop();
        String url = "/resources/category/" + strIds;
        try{
@ -223,7 +225,7 @@ public class RsResourceCategoryController extends EnvelopRestEndpoint {
            return ObjEnvelop.getSuccess("查询成功",rsResourceCategory);
        } catch (Exception e){
            e.printStackTrace();
            return failed(ERR_SYSTEM_DES);
            return ObjEnvelop.getError(ERR_SYSTEM_DES);
        }
    }

+ 26 - 20
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/service/ResourceBrowseControllerService.java

@ -3,13 +3,16 @@ package com.yihu.jw.basic.agadmin.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.basic.quota.service.QuotaService;
import com.yihu.jw.basic.resource.model.RsCategoryTypeTreeModel;
import com.yihu.jw.basic.resource.model.RsResourcesModel;
import com.yihu.jw.basic.resource.service.ResourceBrowseService;
import com.yihu.jw.basic.resource.service.RsResourceCategoryService;
import com.yihu.jw.basic.resource.service.RsResourceQuotaService;
import com.yihu.jw.basic.resource.service.RsResourceService;
import com.yihu.jw.entity.ehr.resource.RsResource;
import com.yihu.jw.entity.ehr.resource.RsResourceCategory;
import com.yihu.jw.entity.ehr.resource.RsResourceQuota;
import com.yihu.jw.restmodel.ehr.resource.MRsCategory;
import com.yihu.jw.restmodel.ehr.resource.MRsColumnsModel;
import com.yihu.jw.restmodel.ehr.resource.MRsResources;
@ -42,7 +45,10 @@ public class ResourceBrowseControllerService {
    private RsResourceCategoryService rsCategoryService;
    @Autowired
    private ResourceBrowseService resourceBrowseService;
    @Autowired
    private RsResourceQuotaService resourceQuotaService;
    @Autowired
    private QuotaService quotaService;
//    @ApiOperation("获取档案资源分类")
//    @RequestMapping(value = ServiceApi.Resources.ResourceBrowseCategories, method = RequestMethod.GET)
@ -86,25 +92,25 @@ public class ResourceBrowseControllerService {
//    @ApiOperation("档案资源浏览")
//    @RequestMapping(value = ServiceApi.Resources.ResourceBrowseResourceData, method = RequestMethod.GET)
//    public Envelop getResourceData(String resourcesCode,String roleId,String orgCode,String areaCode,
//                                   String queryCondition,Integer page,Integer size,String top) throws Exception {
//        RsResource rsResource = rsResourceService.getResourceByCode(resourcesCode);
//        if (!rsResource.getRsInterface().equals("getQuotaData")){//接口 来自接口统计
//            return resourceBrowseClient.getResourceData(resourcesCode, roleId, orgCode, areaCode, queryCondition, page, size);
//        } else {
//            String quotaCodeStr = "";
//            List<ResourceQuotaModel> list = resourceQuotaClient.getByResourceId(rsResourcesModel.getId());
//            if (list != null && list.size() > 0) {
//                for (ResourceQuotaModel resourceQuotaModel : list) {
//                    quotaCodeStr = quotaCodeStr + resourceQuotaModel.getQuotaCode() + ",";
//                }
//            }
//            List<Map<String, Object>> resultList = rsResourceStatisticsClient.getQuotaReportTwoDimensionalTable(quotaCodeStr, null, rsResourcesModel.getDimension(), top);
//            envelop.setDetailModelList(resultList);
//            envelop.setSuccessFlg(true);
//            return  envelop;
//        }
//    }
    public Envelop getResourceData(String resourcesCode,String roleId,String orgCode,String areaCode,
                                   String queryCondition,Integer page,Integer size,String top) throws Exception {
        RsResource rsResource = rsResourceService.getResourceByCode(resourcesCode);
        if (!rsResource.getRsInterface().equals("getQuotaData")){//接口 来自接口统计
            return resourceBrowseService.getResourceData(resourcesCode, roleId, orgCode, areaCode, queryCondition, page, size);
        } else {
            String quotaCodeStr = "";
            List<RsResourceQuota> list = resourceQuotaService.search("resourceId=" + rsResource.getId());
            if (list != null && list.size() > 0) {
                for (RsResourceQuota resourceQuotaModel : list) {
                    quotaCodeStr = quotaCodeStr + resourceQuotaModel.getQuotaCode() + ",";
                }
            }
            List<Map<String, Object>> resultList = quotaService.getQuotaReportTwoDimensionalTable(quotaCodeStr,null,rsResource.getDimension(),top);
            return ListEnvelop.getSuccess("",resultList);
        }
    }
//    @ApiOperation("档案资源浏览细表数据")
//    @RequestMapping(value = ServiceApi.Resources.ResourceBrowseResourceSubData, method = RequestMethod.GET)

+ 3 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/config/Config.java

@ -1,5 +1,7 @@
package com.yihu.jw.basic.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@ -19,4 +21,5 @@ public class Config {
        return container;
    }
}

+ 0 - 26
svr/svr-basic/src/main/java/com/yihu/jw/basic/config/TenantConfiguration.java

@ -1,26 +0,0 @@
//package com.yihu.ehr.config;
//
//import feign.RequestInterceptor;
//import feign.RequestTemplate;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
///**
// *   ehr使用 feginClient 调用eip(涉及到app应用,标准等) 时,需要此类,增加请求头信息
// */
//@Configuration
//public class TenantConfiguration {
//    @Value("${eip.tenant}")
//    private String tenant;
//
//    @Bean
//    public RequestInterceptor tenantInterceptor() {
//        return new RequestInterceptor() {
//            @Override
//            public void apply(RequestTemplate requestTemplate) {
//                requestTemplate.header("tenant_name", tenant);
//            }
//        };
//    }
//}

+ 446 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/es/EsResultExtract.java

@ -0,0 +1,446 @@
package com.yihu.jw.basic.es;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.es.util.ElasticSearchPool;
import com.yihu.jw.basic.es.util.ElasticsearchUtil;
import com.yihu.jw.basic.quota.service.TjDataSaveService;
import com.yihu.jw.entity.ehr.quota.TjDataSave;
import com.yihu.jw.entity.ehr.quota.TjQuota;
import com.yihu.jw.entity.ehr.quota.TjQuotaDataSave;
import com.yihu.jw.restmodel.ehr.quota.EsConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.bucket.terms.DoubleTerms;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2017/6/24
 */
@Component
@Scope("prototype")
public class EsResultExtract {
    private Logger logger = LoggerFactory.getLogger(EsResultExtract.class);
    private String startTime;
    private String endTime;
    private String org;
    private String orgName;
    private String province;
    private String city;
    private String town;
    private String townName;
    private String year;
    private String slaveKey1;
    private String slaveKey2;
    private String result;
    private TjQuota tjQuota;
    private String quotaCode;
    private EsConfig esConfig;
    @Autowired
    ElasticsearchUtil elasticsearchUtil;
    @Autowired
    ElasticSearchPool elasticSearchPool;
    @Autowired
    private TjDataSaveService tjDataSaveService;
    @Autowired
    private ObjectMapper objectMapper;
    public void initialize(TjQuota tjQuota ,String filters) throws Exception {
        this.startTime = null;
        this.endTime = null;
        this.orgName = null;
        this.org = null;
        this.province = null;
        this.city = null;
        this.town = null;
        this.townName = null;
        this.year = null;
        this.quotaCode = null;
        this.result = null;
        this.slaveKey1 = null;
        this.slaveKey2 = null;
        if(!StringUtils.isEmpty(filters)){
            Map<String, Object> params  = objectMapper.readValue(filters, new TypeReference<Map>() {});
            if (params !=null && params.size() > 0){
                for(String key : params.keySet()){
                    if( params.get(key) != null ){
                        if(key.equals("startTime"))
                            this.startTime = params.get(key).toString();
                        else if(key.equals("endTime"))
                            this.endTime = params.get(key).toString();
                        else if(key.equals("orgName"))
                            this.orgName = params.get(key).toString();
                        else if(key.equals("org"))
                            this.org = params.get(key).toString();
                        else if(key.equals("province"))
                            this.province = params.get(key).toString();
                        else if(key.equals("city"))
                            this.city = params.get(key).toString();
                        else if(key.equals("town"))
                            this.town = params.get(key).toString();
                        else if(key.equals("townName"))
                            this.townName = params.get(key).toString();
                        else if(key.equals("year"))
                            this.year = params.get(key).toString();
                        else if(key.equals("slaveKey1"))
                            this.slaveKey1 = params.get(key).toString();
                        else if(key.equals("slaveKey2"))
                            this.slaveKey2 = params.get(key).toString();
                        else if(key.equals("result")){
                            this.result = params.get(key).toString();
                        }
                    }
                }
            }
        }
        this.tjQuota = tjQuota;
        if(null != tjQuota && StringUtils.isNotEmpty(tjQuota.getCode())){
            this.quotaCode = tjQuota.getCode();
        }
        EsConfig esConfig = null;
        esConfig = getEsConfig(tjQuota);
        this.esConfig = esConfig;
    }
    public EsConfig getEsConfig(TjQuota tjQuota) throws Exception {
        //得到该指标的数据存储
        TjQuotaDataSave quotaDataSave = tjDataSaveService.findByQuota(tjQuota.getCode());
        //如果为空说明数据错误
        if (quotaDataSave == null) {
            throw new Exception("quotaDataSave data error");
        }
        //判断数据源是什么类型,根据类型和数据库相关的配置信息抽取数据
        EsConfig esConfig = null;
        if (TjDataSave.type_es.equals(quotaDataSave.getType())) {
            JSONObject obj = new JSONObject().fromObject(quotaDataSave.getConfigJson());
            esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
        }else {
            // wait TO DO
        }
        //初始化es链接
        esConfig = (EsConfig) JSONObject.toBean(JSONObject.fromObject(esConfig), EsConfig.class);
        return esConfig;
    }
    public List<Map<String, Object>> queryResultPage(TjQuota tjQuota ,String filters,int pageNo,int pageSize) throws Exception {
        pageNo = (pageNo-1)*pageSize;
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient client = elasticSearchPool.getClient();
        List<Map<String, Object>> restltList = null;
        try {
            restltList =  elasticsearchUtil.queryPageList(client, esConfig.getIndex(), esConfig.getType(), boolQueryBuilder, pageNo, pageSize,"quotaDate");
        } catch (Exception e){
            e.getMessage();
        }
        return restltList;
    }
    public int getQuotaTotalCount(TjQuota tjQuota,String filters) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient  client = elasticSearchPool.getClient();
        int count  = 0;
        try {
            count  = (int)elasticsearchUtil.getTotalCount(client,esConfig.getIndex(),esConfig.getType(),boolQueryBuilder);
        }catch (Exception e){
            e.getMessage();
        }
        return count;
    }
    public List<Map<String, Object>> getQuotaReport(TjQuota tjQuota, String filters,int size) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient  client = elasticSearchPool.getClient();
        List<Map<String, Object>> list = null;
        try {
           list = elasticsearchUtil.queryList(client,esConfig.getIndex(),esConfig.getType(),boolQueryBuilder, "quotaDate",size);
        }catch (Exception e){
            e.getMessage();
        }
        return  list;
    }
    public BoolQueryBuilder getBoolQueryBuilder(BoolQueryBuilder boolQueryBuilder){
        if( !StringUtils.isEmpty(result)){
            if( !result.equals("qb")){//查全部
                result = "1";
                RangeQueryBuilder rangeQueryResult = QueryBuilders.rangeQuery("result").gte(result);
                boolQueryBuilder.must(rangeQueryResult);
            }
        }
        if( !StringUtils.isEmpty(quotaCode)){
//            TermQueryBuilder termQueryQuotaCode = QueryBuilders.termQuery("quotaCode", quotaCode);
            if(esConfig.getType().equals("orgHealthCategoryQuota")){
                QueryStringQueryBuilder termQuotaCode = QueryBuilders.queryStringQuery("orgHealthCategoryQuotaCode:" + quotaCode.replaceAll("_",""));
                boolQueryBuilder.must(termQuotaCode);
            }else{
                QueryStringQueryBuilder termQuotaCode = QueryBuilders.queryStringQuery("quotaCode:" + quotaCode.replaceAll("_",""));
                boolQueryBuilder.must(termQuotaCode);
            }
        }
        BoolQueryBuilder qbChild =  QueryBuilders.boolQuery();
        if( !StringUtils.isEmpty(orgName) ){
//            TermQueryBuilder termQueryOrgName = QueryBuilders.termQuery("orgName", orgName);
            QueryStringQueryBuilder termOrgName = QueryBuilders.queryStringQuery("orgName:" + orgName);
            boolQueryBuilder.must(termOrgName);
        }
        if( !StringUtils.isEmpty(org) ){
            String [] orgvals =org.split(",");
            for(int i=0;i<orgvals.length ; i++){
                MatchQueryBuilder termOrg = QueryBuilders.matchPhraseQuery("org", orgvals[i]);
                qbChild.should(termOrg);
            }
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(slaveKey1) ){
            QueryStringQueryBuilder termSlaveKey1 = QueryBuilders.queryStringQuery("slaveKey1:" + slaveKey1);
            qbChild.should(termSlaveKey1);
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(slaveKey2) ){
            QueryStringQueryBuilder termSlaveKey2 = QueryBuilders.queryStringQuery("slaveKey2:" + slaveKey2);
            qbChild.should(termSlaveKey2);
            boolQueryBuilder.must(qbChild);
        }
        if( !StringUtils.isEmpty(province) ){
            QueryStringQueryBuilder termProvince = QueryBuilders.queryStringQuery("province:" + province);
            boolQueryBuilder.must(termProvince);
        }
        if( !StringUtils.isEmpty(city) ){
            QueryStringQueryBuilder termCity = QueryBuilders.queryStringQuery("city:" + city);
            boolQueryBuilder.must(termCity);
        }
        if( !StringUtils.isEmpty(town) ){
            QueryStringQueryBuilder termTown = QueryBuilders.queryStringQuery("town:" + town);
            boolQueryBuilder.must(termTown);
        }
        if( !StringUtils.isEmpty(townName) ){
            QueryStringQueryBuilder termTown = QueryBuilders.queryStringQuery("townName:" + townName);
            boolQueryBuilder.must(termTown);
        }
        if( !StringUtils.isEmpty(year) ){
            QueryStringQueryBuilder termYear = QueryBuilders.queryStringQuery("year:" + year);
            boolQueryBuilder.must(termYear);
        }
        if( !StringUtils.isEmpty(startTime) ){
            RangeQueryBuilder rangeQueryStartTime = QueryBuilders.rangeQuery("quotaDate").gte(startTime);
            boolQueryBuilder.must(rangeQueryStartTime);
        }
        if( !StringUtils.isEmpty(endTime)){
            RangeQueryBuilder rangeQueryEndTime = QueryBuilders.rangeQuery("quotaDate").lte(endTime);
            boolQueryBuilder.must(rangeQueryEndTime);
        }
        return boolQueryBuilder;
    }
    /**
     * 递归解析json
     *
     * @param gradeBucketIt
     * @param map
     * @param sb
     */
    private void expainJson(Iterator<Terms.Bucket> gradeBucketIt, Map<String,Integer>map, StringBuffer sb) {
        while (gradeBucketIt.hasNext()) {
            Terms.Bucket b =  gradeBucketIt.next();
            if (b.getAggregations().asList().get(0) instanceof StringTerms) {
                StringTerms stringTermsCh = (StringTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = stringTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof LongTerms) {
                LongTerms longTermsCh = (LongTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = longTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof DoubleTerms) {
                DoubleTerms doubleTermsCh = (DoubleTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = doubleTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else {
                if (b.getAggregations().asList().get(0) instanceof InternalValueCount) {
                    InternalValueCount count = (InternalValueCount) b.getAggregations().asList().get(0);
                    map.put(new StringBuffer((sb == null ? "" : (sb.toString() + "-"))+ b.getKey()).toString() , (int)count.getValue());
                }else if (b.getAggregations().asList().get(0) instanceof InternalSum) {
                    InternalSum count = (InternalSum) b.getAggregations().asList().get(0);
                    map.put(new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + "-" + b.getKey()).toString() , (int)count.getValue());
                }
            }
        }
    }
    //指标分组统计数量 - 只支持一个字段
    public List<Map<String, Object>> searcherByGroup(TjQuota tjQuota, String filters,String aggsField ) throws Exception {
        initialize(tjQuota,filters);
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery();
        getBoolQueryBuilder(boolQueryBuilder);
        TransportClient client = elasticSearchPool.getClient();
        List<Map<String, Object>> list = null;
        try {
            list = elasticsearchUtil.searcherByGroup(client,esConfig.getIndex(),esConfig.getType(), boolQueryBuilder, aggsField, "result");
        } catch (Exception e){
            e.getMessage();
        }
        return  list;
    }
    //根据mysql 指标分组求和 支持一个和多个字段
    public Map<String, Integer> searcherSumByGroupBySql(TjQuota tjQuota , String aggsFields ,String filter, String sumField,String orderFild,String order) throws Exception {
        initialize(tjQuota,null);
        if(StringUtils.isEmpty(filter)){
            filter =  " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        }else {
            filter = filter + " and quotaCode='" + tjQuota.getCode().replaceAll("_","") + "' ";
        }
        TransportClient client = elasticSearchPool.getClient();
        Map<String, Integer> map = null;
        try {
            map = elasticsearchUtil.searcherSumByGroupBySql(client, esConfig.getIndex(), aggsFields, filter, sumField,orderFild,order);;
        } catch (Exception e){
            e.getMessage();
        }
        return map;
    }
    /**
     * //根据mysql 指标分组 按时间聚合
     * @param tjQuota
     * @param aggsFields
     * @param filter
     * @param dateDime
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> searcherSumByGroupByTime(TjQuota tjQuota , String aggsFields ,String filter,String dateDime) throws Exception {
        initialize(tjQuota,null);
        String quotaCode = " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        if(StringUtils.isEmpty(filter)){
            filter =  quotaCode;
        }else {
            filter += " and " + quotaCode;
        }
        if(StringUtils.isNotEmpty(aggsFields)){
            aggsFields += ",";
        }
        try {
            //SELECT sum(result) FROM medical_service_index group by town,date_histogram(field='quotaDate','interval'='year')
            StringBuffer mysql = new StringBuffer("SELECT ")
                    .append(aggsFields)
                    .append(" sum(result) FROM ").append(esConfig.getIndex())
                    .append(" where quotaDate is not null and ").append(filter)
                    .append(" group by ").append(aggsFields)
                    .append(" date_histogram(field='quotaDate','interval'='")
                    .append(dateDime).append("')").append(" limit 10000 ");
            logger.warn("查询分组 mysql= " + mysql.toString());
            List<Map<String, Object>> listMap = elasticsearchUtil.excuteDataModel(mysql.toString());
            if(listMap != null &&  listMap.size() > 0){
                if(listMap.get(0).get("SUM(result)") != null){
                    return  listMap;
                }
            }
            return  new ArrayList<>();
        } catch (Exception e){
            e.getMessage();
        }
        return null;
    }
    /**
     * 根据sql  分组统计数据
     * @param tjQuota
     * @param aggsFields
     * @param filter
     * @param sumField
     * @param orderFild
     * @param order
     * @return
     * @throws Exception
     */
    public  List<Map<String, Object>>  searcherSumGroup(TjQuota tjQuota , String aggsFields ,String filter, String sumField,String orderFild,String order, String top) throws Exception {
        initialize(tjQuota,null);
        String quotaCode = " quotaCode='" + tjQuota.getCode().replaceAll("_", "") + "' ";
        if(StringUtils.isEmpty(filter)){
            filter =  quotaCode;
        }else {
            filter += " and " + quotaCode;
        }
        try {
            StringBuffer mysql = new StringBuffer("select ");
            mysql.append(aggsFields)
                    .append(" ,sum(").append(sumField).append(") ")
                    .append(" from ").append(esConfig.getIndex())
                    .append(" where quotaDate is not null and ").append(filter)
                    .append(" group by ").append(aggsFields);
            if(StringUtils.isNotEmpty(orderFild) && StringUtils.isNotEmpty(order)){
                if (StringUtils.isNotEmpty(top)) {
                    mysql.append(" order by sum(").append(sumField).append(") desc");
                } else {
                    mysql.append(" order by ").append(orderFild).append(" ").append(order);
                }
            }
            if (StringUtils.isNotEmpty(top)) {
                mysql.append(" limit ").append(top);
            } else {
                mysql.append(" limit 10000 ");
            }
            logger.warn("查询分组 mysql= " + mysql.toString());
            List<Map<String, Object>> listMap = elasticsearchUtil.excuteDataModel(mysql.toString());
            if(listMap != null &&  listMap.size() > 0){
                if(listMap.get(0).get("SUM(result)") != null){
                    return  listMap;
                }
            }
            return  new ArrayList<>();
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }
}

+ 45 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticSearchConfig.java

@ -0,0 +1,45 @@
package com.yihu.jw.basic.es.util;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
 * Created by progr1mmer on 2017/12/1.
 */
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
public class ElasticSearchConfig {
    // 集群名称
    private String clusterName;
    // 节点
    private String clusterNodes;
    public String getClusterName() {
        return clusterName;
    }
    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }
    public String getClusterNodes() {
        return clusterNodes;
    }
    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }
    @PostConstruct
    private void configInfo() {
        StringBuilder info = new StringBuilder("{");
        info.append("\n  elasticsearch.cluster-name = " + clusterName);
        info.append("\n  elasticsearch.cluster-nodes = " + clusterNodes);
        info.append("\n}");
        System.out.println("Elasticsearch.configInfo : " + info.toString());
    }
}

+ 80 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticSearchPool.java

@ -0,0 +1,80 @@
package com.yihu.jw.basic.es.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.ElasticSearchDruidDataSourceFactory;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetSocketAddress;
import java.util.Properties;
/**
 * Created by progr1mmer on 2018/1/4.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ElasticSearchPool {
    private static volatile TransportClient transportClient;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;
    private TransportClient getTransportClient() {
        Settings settings = Settings.builder()
                .put("cluster.name", elasticSearchConfig.getClusterName())
                .put("client.transport.sniff", false)
                .build();
        String[] nodeArr = elasticSearchConfig.getClusterNodes().split(",");
        InetSocketTransportAddress[] socketArr = new InetSocketTransportAddress[nodeArr.length];
        for (int i = 0; i < socketArr.length; i++) {
            if (!StringUtils.isEmpty(nodeArr[i])) {
                String[] nodeInfo = nodeArr[i].split(":");
                socketArr[i] = new InetSocketTransportAddress(new InetSocketAddress(nodeInfo[0], new Integer(nodeInfo[1])));
            }
        }
        return TransportClient.builder().settings(settings).build().addTransportAddresses(socketArr);
    }
    /**
     * 1.TransportClient本身支持多线程的数据请求
     * 2.移除多个TransportClient的线程池支持,减少Socket链接
     * 3.基于多重检查的单例模式,兼顾安全和效率
     * 4.为提高效率,使用完毕后请勿进行 transportClient.close() 的关闭操作
     * @return
     */
    public TransportClient getClient() {
        if (transportClient != null) {
            if (transportClient.connectedNodes().isEmpty()) {
                synchronized (TransportClient.class) {
                    if (transportClient.connectedNodes().isEmpty()) {
                        transportClient = getTransportClient();
                    }
                }
            }
            return transportClient;
        }
        synchronized (TransportClient.class) {
            if (null == transportClient) {
                transportClient = getTransportClient();
            }
        }
        return transportClient;
    }
    public DruidDataSource getDruidDataSource() throws Exception {
        Properties properties = new Properties();
        properties.put("url", "jdbc:elasticsearch://" + elasticSearchConfig.getClusterNodes() + "/");
        DruidDataSource druidDataSource = (DruidDataSource) ElasticSearchDruidDataSourceFactory
                .createDataSource(properties);
        druidDataSource.setInitialSize(1);
        return druidDataSource;
    }
}

+ 402 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/ElasticsearchUtil.java

@ -0,0 +1,402 @@
package com.yihu.jw.basic.es.util;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.sql.parser.SQLExprParser;
import com.alibaba.druid.sql.parser.Token;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.sum.SumBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.jdbc.ObjectResult;
import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
import org.nlpcn.es4sql.parse.SqlParser;
import org.nlpcn.es4sql.query.AggregationQueryAction;
import org.nlpcn.es4sql.query.DefaultQueryAction;
import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
/**
 * Created by janseny on 2017/7/21.
 */
@Component
public class ElasticsearchUtil {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private ElasticSearchPool elasticSearchPool;
    /**
     * @param boolQueryBuilder  查询参数 build
     * @param pageNo
     * @param pageSize
     * @param sortName 排序字段名称
     * @return
     */
    public List<Map<String, Object>> queryPageList(Client client, String index, String type, BoolQueryBuilder boolQueryBuilder,
                                                   int pageNo, int pageSize, String sortName){
        SearchResponse actionGet = null;
        SortBuilder dealSorter = SortBuilders.fieldSort(sortName).order(SortOrder.DESC);
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setQuery(boolQueryBuilder)
                .setFrom(pageNo - 1).setSize(pageSize).addSort(dealSorter)//从0开始算
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()){
            matchRsult.add(hit.getSource());
        }
        return matchRsult;
    }
    /**
     * @param boolQueryBuilder  查询参数 build
     * @return
     */
    public long getTotalCount(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder){
        SearchResponse actionGet = null;
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setQuery(boolQueryBuilder)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
       if(hits != null){
           return hits.totalHits();
       }
        return 0;
    }
    /**
     * @param boolQueryBuilder  查询参数 build
     * @param sortName 排序字段名称
     * @return
     */
    public List<Map<String, Object>> queryList(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder,String sortName,int size){
        SearchResponse actionGet = null;
        SortBuilder dealSorter = null;
        if(sortName != null){
            dealSorter = SortBuilders.fieldSort(sortName).order(SortOrder.DESC);
        }else{
            dealSorter = SortBuilders.fieldSort("_id").order(SortOrder.DESC);
        }
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setSize(size)
                .setQuery(boolQueryBuilder)
                .addSort(dealSorter)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>();
        for (SearchHit hit : hits.getHits()){
            Map<String, Object> map = new HashMap<>() ;
            map = hit.getSource();
            map.put("id",hit.getId());
            matchRsult.add(map);
        }
        return matchRsult;
    }
    /**
     * 执行搜索(带分组求和sum)
     * @param queryBuilder 查询内容
     * @param aggsField 要分组的字段
     * @param sumField 要求和的字段  只支持一个字段
     * @return
     */
    public List<Map<String, Object>> searcherByGroup(Client client, String index, String type, BoolQueryBuilder queryBuilder, String aggsField , String sumField) {
        List<Map<String, Object>> list = new ArrayList<>();
        SearchRequestBuilder searchRequestBuilder =
                client.prepareSearch(index)
                .setTypes(type)
                .setQuery(queryBuilder);
        //创建TermsBuilder对象,使用term查询,设置该分组的名称为 name_count,并根据aggsField字段进行分组
        TermsBuilder termsBuilder = AggregationBuilders.terms(aggsField+"_val").field(aggsField);
        SumBuilder ageAgg = AggregationBuilders.sum(sumField+"_count").field(sumField);
        searchRequestBuilder.addAggregation(termsBuilder.subAggregation(ageAgg));
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //执行搜索
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        //解析返回数据,获取分组名称为aggs-class的数据
        Terms terms = searchResponse.getAggregations().get(aggsField+"_val");
        Collection<Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKey().toString();
            if (bucket.getAggregations().asList().get(0) instanceof InternalSum) {//(sum(xx))
                InternalSum count = (InternalSum) bucket.getAggregations().asList().get(0);
                dataMap.put(key, count.value());
            }
        }
        list.add(dataMap);
        return list;
    }
    /**
     * 根据mysql 语句进行分组求和查询
     * @param client
     * @param index 索引名称
     * @param aggsFields 分组字段 支持多个
     * @param filter 条件
     * @param sumField  求和字段
     * @param orderFild 排序字段
     * @param order 排序 asc,desc
     * @return
     */
    public Map<String, Integer> searcherSumByGroupBySql(Client client,String index, String aggsFields ,String filter , String sumField,String orderFild,String order) throws Exception {
        Map<String,Integer> map = new LinkedHashMap<>();
//       String mysql1 = "select org ,sum(result) from quota where quotaCode='depart_treat_count' group by org  ";id=16
        StringBuffer mysql = new StringBuffer("select ");
        mysql.append(aggsFields)
             .append(" ,sum(").append(sumField).append(") ")
             .append(" from ").append(index)
             .append(" where ").append(filter)
             .append(" group by ").append(aggsFields);
        if (StringUtils.isNotEmpty(orderFild) && StringUtils.isNotEmpty(order)){
            mysql.append(" order by ").append(orderFild).append(" ").append(order);
        }
        System.out.println("查询分组 mysql= " + mysql.toString());
        SQLExprParser parser = new ElasticSqlExprParser(mysql.toString());
        SQLExpr expr = parser.expr();
        if (parser.getLexer().token() != Token.EOF) {
            throw new ParserException("illegal sql expr : " + mysql);
        }
        SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
        //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
        Select select = null;
        select = new SqlParser().parseSelect(queryExpr);
        AggregationQueryAction action = null;
        DefaultQueryAction queryAction = null;
        SqlElasticSearchRequestBuilder requestBuilder = null;
        if (select.isAgg) {
            //包含计算的的排序分组的
            action = new AggregationQueryAction(client, select);
            requestBuilder = action.explain();
        } else {
            //封装成自己的Select对象
            queryAction = new DefaultQueryAction(client, select);
            requestBuilder = queryAction.explain();
        }
        //之后就是对ES的操作
        SearchResponse response = (SearchResponse) requestBuilder.get();
        StringTerms stringTerms = (StringTerms) response.getAggregations().asList().get(0);
        Iterator<Terms.Bucket> gradeBucketIt = stringTerms.getBuckets().iterator();
        //里面存放的数据 例  350200-5-2-2    主维度  细维度1  细维度2  值
        //递归解析json
        expainJson(gradeBucketIt, map, null);
        return map;
    }
    /**
     *
     * @param client
     * @param source 表字段组合json格式
     * @return
     * @throws JsonProcessingException
     */
    public boolean save(Client client,String index,String type,String source) throws JsonProcessingException {
        IndexResponse indexResponse = client
                .prepareIndex(index, type, null)
                .setSource(source).get();
        boolean result =  indexResponse.isCreated();
        return result;
    }
    /**
     * 查询后 存在 删除
     * @param boolQueryBuilder
     */
    public synchronized  boolean queryDelete(Client client,String index,String type,BoolQueryBuilder boolQueryBuilder){
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        DeleteRequestBuilder deleteRequestBuilder = null ;
        SearchResponse actionGet = null;
        actionGet = client.prepareSearch(index)
                .setTypes(type)
                .setSize(10000)
                .setQuery(boolQueryBuilder)
                .execute().actionGet();
        SearchHits hits = actionGet.getHits();
        for (SearchHit hit : hits.getHits()){
            deleteRequestBuilder = client.prepareDelete(index, type, hit.getId());
            bulkRequestBuilder.add(deleteRequestBuilder.request());
        }
        //进行批量删除操作
        boolean optFlag = true;
        if(hits.getHits() != null && hits.getHits().length > 0){
            BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
            if (bulkResponse.hasFailures()) {
                optFlag = false;
            }else {
                optFlag = true;
            }
        }
        return  optFlag;
    }
    /**
     * 递归解析json
     *
     * @param gradeBucketIt
     * @param map
     * @param sb
     */
    private void expainJson(Iterator<Terms.Bucket> gradeBucketIt,Map<String,Integer> map, StringBuffer sb) {
        while (gradeBucketIt.hasNext()) {
            Terms.Bucket b =  gradeBucketIt.next();
            if (b.getAggregations().asList().get(0) instanceof StringTerms) {
                StringTerms stringTermsCh = (StringTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = stringTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof LongTerms) {
                LongTerms longTermsCh = (LongTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = longTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof DoubleTerms) {
                DoubleTerms doubleTermsCh = (DoubleTerms) b.getAggregations().asList().get(0);
                Iterator<Terms.Bucket> gradeBucketItCh = doubleTermsCh.getBuckets().iterator();
                while (gradeBucketItCh.hasNext()) {
                    StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                    expainJson(gradeBucketItCh, map, sbTemp);
                }
            }else if (b.getAggregations().asList().get(0) instanceof InternalValueCount) {//count(8)
                InternalValueCount count = (InternalValueCount) b.getAggregations().asList().get(0);
                StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                map.put(sbTemp.toString() , (int)count.getValue());
            }else if (b.getAggregations().asList().get(0) instanceof InternalSum) {//(sum(xx))
                InternalSum count = (InternalSum) b.getAggregations().asList().get(0);
                StringBuffer sbTemp = new StringBuffer((sb == null ? "" : (sb.toString() + "-")) + b.getKey());
                map.put(sbTemp.toString() , (int)count.getValue());
            }
        }
    }
    /**
     * 执行sql查询es
     * @param sql
     * @return
     */
    public List<Map<String, Object>> excuteDataModel(String sql) {
        List<Map<String, Object>> returnModels = new ArrayList<>();
        TransportClient client = elasticSearchPool.getClient();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(client, select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || sql.toUpperCase().indexOf("COUNT") != -1) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                try {
                    Map<String, Object> oneMap = new HashMap<String, Object>();
                    for (int i = 0; i < one.size(); i++) {
                        String key = null;
                        Object value = one.get(i);
                        key = heads.get(i);
                        oneMap.put(key, value);
                    }
                    returnModels.add(oneMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnModels;
    }
    public long getCountBySql(String sql) {
        TransportClient client = elasticSearchPool.getClient();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(client, select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            SearchHits hits = response.getHits();
            if(hits != null){
                return hits.totalHits();
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

+ 58 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/es/util/EsClientUtil.java

@ -0,0 +1,58 @@
package com.yihu.jw.basic.es.util;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
/**
* Created by janseny on 2017/8/1
 */
@Component
public class EsClientUtil {
    private Logger logger = LoggerFactory.getLogger(EsClientUtil.class);
    /**
     * @param host "localhost"
     * @param port 9200
     * @return
     */
    public JestClient getJestClient(String host, Integer port) {
        String hostAddress="http://"+host+":"+port;
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder(hostAddress)
                .multiThreaded(true)
                //.discoveryEnabled(true)
                .readTimeout(60000)//30秒 -60s
                .build());
        return factory.getObject();
    }
    public Client getClient(String host, Integer port,String clusterName) {
        try {
            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", StringUtils.isEmpty(clusterName)?"elasticsearch":clusterName)
                    .put("client.transport.sniff", false)
                    .build();
            Client client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

+ 926 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/QuotaReportController.java

@ -0,0 +1,926 @@
package com.yihu.jw.basic.quota.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.basic.quota.service.*;
import com.yihu.jw.basic.resource.service.RsResourceQuotaService;
import com.yihu.jw.basic.util.BasesicUtil;
import com.yihu.jw.basic.util.ReportOption;
import com.yihu.jw.basic.util.model.ChartDataModel;
import com.yihu.jw.entity.ehr.quota.TjQuota;
import com.yihu.jw.entity.ehr.quota.TjQuotaDimensionMain;
import com.yihu.jw.entity.ehr.quota.TjQuotaDimensionSlave;
import com.yihu.jw.entity.ehr.resource.RsResourceQuota;
import com.github.abel533.echarts.Option;
import com.yihu.jw.restmodel.ehr.report.MQcDevice;
import com.yihu.jw.restmodel.ehr.resource.MChartInfoModel;
import com.yihu.jw.restmodel.ehr.resource.MRsResources;
import com.yihu.jw.restmodel.ehr.tj.DictModel;
import com.yihu.jw.restmodel.ehr.tj.SaveModel;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author janseny
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(description = "指标报表统计 -指标报表统计控制入口")
public class QuotaReportController extends EnvelopRestEndpoint {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private TjDimensionMainService tjDimensionMainService;
    @Autowired
    private TjDimensionSlaveService tjDimensionSlaveService;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RsResourceQuotaService resourceQuotaService;
    @Autowired
    private OrgHealthCategoryStatisticsService orgHealthCategoryStatisticsService;
    @Autowired
    private BaseStatistsService baseStatistsService;
    @Autowired
    private DeviceService deviceService;
    private BasesicUtil basesicUtil = new BasesicUtil();
    public static String orgHealthCategoryCode = "orgHealthCategoryCode";
    @RequestMapping(value = ServiceApi.TJ.GetYearDropdownList, method = RequestMethod.GET)
    @ApiOperation(value = "获取二维表查询年份下拉数据")
    public Envelop getDropdownList(
            @ApiParam(name = "type", value = "类型 1增量型报表 2 全量型报表")
            @RequestParam(value = "type" ,required =  true ) int type,
            @ApiParam(name = "index", value = "索引")
            @RequestParam(value = "index" ,required =  true ) String index) throws Exception {
        Envelop envelop = new Envelop();
        Map<String, List<String>> map = null;
        String sql = "select count(1) from "+ index +" group by date_histogram(field='quotaDate','interval'='year') order by quotaDate desc";
        map = baseStatistsService.getDataInfo(sql, "date_histogram(field=quotaDate,interval=year)");
        if (null != map && map.size() > 0) {
            Collections.sort(map.get("xData"), Collections.reverseOrder());
            if(type == 1){
                return ObjEnvelop.getSuccess("查询成功",map.get("xData"));
            }else {
                Map<String,String> resultMap = new HashMap<>();
                for(String key : map.get("xData")){
                    String filter = "quotaDate >= '" + key + "-01-01'" + " and quotaDate <= '" + key +"-12-31'";
                    sql = "select count(1) from "+ index +" where " + filter + " group by date_histogram(field='quotaDate','interval'='month') order by quotaDate desc";
                    System.out.println(sql);
                    Map<String, List<String>>  monthMap = baseStatistsService.getDataInfo(sql, "date_histogram(field=quotaDate,interval=month)");
                    if(monthMap != null && monthMap.size() > 0){
                        resultMap.put(key,monthMap.get("xData").get(0).toString());
                    }
                }
                return ObjEnvelop.getSuccess("查询成功",resultMap);
            }
        }
        return  success();
    }
    /**
     * 获取指标统计结果
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取指标统计结果")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaReport, method = RequestMethod.GET)
    public Envelop getQuotaReport(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id", required = true) int id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension
    ) {
        Envelop envelop = new Envelop();
        try {
            return success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return failed("查询失败");
    }
    @ApiOperation(value = "获取统计报表一个视图下多个指标组合  二维表数据")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaReportTwoDimensionalTable, method = RequestMethod.GET)
    public List<Map<String, Object>> getQuotaReportTwoDimensionalTable(
            @ApiParam(name = "quotaCodeStr", value = "指标Code,多个用,拼接", required = true)
            @RequestParam(value = "quotaCodeStr", required = true) String quotaCodeStr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        return quotaService.getQuotaReportTwoDimensionalTable(quotaCodeStr,filter,dimension,top);
    }
    /**
     * 判断指标统计中 总计 是否已经计算过
     * @param code
     * @param dataList
     * @return
     */
    private String existsTotal(String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get("firstColumn") != null && map.get("firstColumn").toString().equals("合计") && map.get(code) != null){
                if(map.get(code).toString().equals("--")){
                    return "false";
                }else {
                    return map.get(code).toString();
                }
            }
        }
        return "false";
    }
    /**
     * 统计每列合计
     * @param sum
     * @param code
     * @param dataList
     * @return
     */
    private double calculateSum( double sum,String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get(code) != null){
                sum += Double.valueOf("--".equals(map.get(code)) ? "0" : map.get(code).toString());
            }
        }
        return sum;
    }
    @ApiOperation(value = "获取指标统计结果echart图表,支持多条组合")
    @RequestMapping(value = ServiceApi.TJ.GetMoreQuotaGraphicReportPreviews, method = RequestMethod.GET)
    public Envelop getQuotaGraphicReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
            @ApiParam(name = "charstr", value = "多图表类型用,拼接,混合类型只支持柱状和线性", defaultValue = "1")
            @RequestParam(value = "charstr", required = true) String charstr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top,
            @ApiParam(name = "MRsResource json串")
            @RequestParam(value = "mRsResource", required = false) String mRsResource
            ) {
        String xName = "";
        String yName = "";
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        List<String> charTypes = Arrays.asList(charstr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        String dimensionName = dimension + "Name";
        if ("quotaName".equals(dimension)) {
            dimensionName = "quotaName";
        }
        try {
            Option option = null;
            List<List<Object>> optionData = new ArrayList<>();
            List<String> lineNames = new ArrayList<>();
            Map<String, Map<String, Object>> lineData = new LinkedHashMap<>();
            Map<String, String> xAxisMap = new LinkedHashMap<>();
            Integer i = 0;
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new LinkedHashMap<>();
                TjQuota tjQuota = quotaService.findOne(Long.valueOf(quotaId));
                if (tjQuota != null) {
                    List<Map<String, Object>> resultListMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension,true, top);
                    if (resultListMap != null && resultListMap.size() > 0) {
                        for (Map<String, Object> map : resultListMap) {
                            if (map != null && map.size() > 0) {
                                if (map.containsKey("quotaName")) {
                                    map.put("quotaName",tjQuota.getName());
                                }
                                listMap.add(map);
                                //第一种 ES库中有定义的维度 如org,slaveKey1
                                //第二种 ES库中未定义的维度 如level,economic
                                if (map.containsKey(dimensionName)) {
                                    if(map.get(dimensionName) != null){
                                        dataMap.put(map.get(dimensionName).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimensionName).toString(), map.get(dimension).toString());
                                    }
                                } else {
                                    if(map.get(dimension) != null){
                                        dataMap.put(map.get(dimension).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimension).toString(), map.get(dimension).toString());
                                    }
                                }
                            }
                        }
                    }
                    lineData.put("" + i, dataMap);
                    lineNames.add(tjQuota.getName());
                    i++;
                }
            }
//            lineNames.add(title);
//            lineData.put("", dataMap);
            Map<String, Object> quotaMap = new LinkedHashMap<>();
            ReportOption reportOption = new ReportOption();
            int size = 0;
            String quota = "0";
            if (lineData != null && lineData.size() > 0) {
                for (String key : lineData.keySet()) {
                    int tempSize = lineData.get(key).size();
                    if (tempSize > size) {
                        size = tempSize;
                        quota = key;
                        quotaMap = lineData.get(key);
                    }
                }
                for (String key : lineData.keySet()) {
                    List<Object> dataList = new ArrayList<>();
                    Map<String, Object> valMap = lineData.get(key);
                    if (key != quota) {
                        for (String name : quotaMap.keySet()) {
                            if (valMap.containsKey(name)) {
                                dataList.add(valMap.get(name));
                            } else {
                                dataList.add(0);
                            }
                        }
                    } else {
                        for (String name : valMap.keySet()) {
                            dataList.add(valMap.get(name));
                        }
                    }
                    optionData.add(dataList);
                }
            }
            Object[] xData = (Object[]) quotaMap.keySet().toArray(new Object[quotaMap.size()]);
            for (String typeStr : charTypes) {
                if (typeStr.equals("common")) {
                    typeStr = "1";
                } else if (typeStr.equals("twoDimensional")) { // 这个需要与前端商榷  访问2次(二维表类型)
                    return null;
                }
                int type = Integer.valueOf(typeStr);
                String dataMeasurement = "";
                if (StringUtils.isNotEmpty(mRsResource)) {
                    MRsResources mRsResources = objectMapper.readValue(mRsResource, MRsResources.class);
                    dataMeasurement = mRsResources.getDataMeasurement();
                    String dataPosition = mRsResources.getDataPosition();
                    if (StringUtils.isNotEmpty(dataPosition) && "x".equalsIgnoreCase(dataPosition)) {
                        xName = "单位:" + mRsResources.getDataUnit();
                    } else if (StringUtils.isNotEmpty(dataPosition) && "y".equalsIgnoreCase(dataPosition)) {
                        yName = "单位:" + mRsResources.getDataUnit();
                    }
                }
                if (type == ReportOption.bar) {
                    option = reportOption.getLineEchartOptionMoreChart(title, xName, yName, xData, discountByMeasurement(optionData, dataMeasurement), lineNames, charTypes);
                } else if (type == ReportOption.line) {
                    option = reportOption.getLineEchartOptionMoreChart(title, xName, yName, xData, discountByMeasurement(optionData, dataMeasurement), lineNames, charTypes);
                } else if (type == ReportOption.pie) {
                    List<Map<String, Object>> datalist = new ArrayList<>();
                    for (Map<String, Object> resultMap : listMap) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("NAME", null == resultMap.get(dimensionName) ? resultMap.get(dimension) : resultMap.get(dimensionName));
                        map.put("TOTAL", resultMap.get("result"));
                        if(resultMap.get(dimensionName) != null){
                            map.put("NAME",resultMap.get(dimensionName));
                        }else {
                            //非 指标中配置的维度 关联出来的字段
                            if(dimensionName.equals("levelName")){
                                if(resultMap.get(dimension).equals("1")){
                                    map.put("NAME","一级医院");
                                }else  if(resultMap.get(dimension).equals("2")){
                                    map.put("NAME","二级医院");
                                }else  if(resultMap.get(dimension).equals("3")){
                                    map.put("NAME","三级医院");
                                }
                            }
                        }
                        map.put("TOTAL",resultMap.get("result"));
                        datalist.add(map);
                    }
                    option = reportOption.getPieEchartOption(title, "", "", datalist, lineNames.get(0), null);
                }
            }
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return ObjEnvelop.getSuccess("",chartInfoModel);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
//    @ApiOperation(value = "获取指标统计结果echart图表,支持多条组合")
//    @RequestMapping(value = ServiceApi.TJ.GetMoreQuotaGraphicReportPreviews, method = RequestMethod.GET)
//    public MChartInfoModel getQuotaGraphicReports(
//            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
//            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
//            @ApiParam(name = "charstr", value = "多图表类型用,拼接,混合类型只支持柱状和线性", defaultValue = "1")
//            @RequestParam(value = "charstr" , required = true) String charstr,
//            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
//            @RequestParam(value = "filter", required = false) String filter,
//            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
//            @RequestParam(value = "dimension", required = false) String dimension,
//            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
//            @RequestParam(value = "title", required = false) String title
//    ) {
//        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
//        List<String> charTypes = Arrays.asList(charstr.split(","));
//        MChartInfoModel chartInfoModel = new MChartInfoModel();
//        try {
//            Option option = null;
//            List<List<Object>> optionData = new ArrayList<>();
//            List<String> lineNames = new ArrayList<>();
//            Map<String,Map<String, Object>> lineData = new LinkedHashMap<>();
//            Map<String, String> xAxisMap = new LinkedHashMap<>();
//            for(String quotaId:quotaIds){
//                Map<String, Object> dataMap = new LinkedHashMap<>();
//                TjQuota tjQuota = quotaService.findOne(Integer.valueOf(quotaId));
//                if(tjQuota != null){
//                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(),dimension);
//                    Map<String,String> dimensionDicMap = new HashMap<>();
//                    if(StringUtils.isNotEmpty(dictSql)){
//                        BasesicUtil baseUtil = new BasesicUtil();
//                        if(dimension.contains("slaveKey")){
//                            //查询字典数据
//                            List<DictModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(DictModel.class));
//                            for (DictModel dictModel : dictDatas) {
//                                String name = baseUtil.getFieldValueByName("name", dictModel);
//                                String val = baseUtil.getFieldValueByName("code", dictModel).toLowerCase();
//                                dimensionDicMap.put(val,name);
//                            }
//                        } else{
//                            List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
//                            if(dictDatas != null ) {
//                                for (SaveModel saveModel : dictDatas) {
//                                    String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
//                                    String val = baseUtil.getFieldValueByName(dimension,saveModel).toLowerCase();
//                                    dimensionDicMap.put(val,name);
//                                }
//                            }
//                        }
//                    }
//
//                    Map<String, Object> groupDataMap = new HashMap<>();
//                    if(tjQuota.getResultGetType().trim().equals("1")){
//                        //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
//                        Map<String, Integer> resultDataMap =  quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter,"result","","");
//                        for(String key: resultDataMap.keySet()){
//                            groupDataMap.put(key,resultDataMap.get(key));
//                        }
//                    }else{//二次统计指标获取 结果接口
//                        List<Map<String, Object>> listMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension);
//                        if(listMap != null && listMap.size() > 0){
//                            for(Map<String, Object> map : listMap){
//                                String keyName = "";
//                                String val = "";
//                                for (String key : map.keySet()) {
//                                    if ("result".equals(key)) {
//                                        val = map.get(key).toString();
//                                    } else {
//                                        keyName = map.get(key).toString();
//                                    }
//                                }
//                                groupDataMap.put(keyName, val);
//                            }
//                        }
//
//                    }
//
//                    for(String key : groupDataMap.keySet()){
//                        key = key.toLowerCase();
//                        dataMap.put(dimensionDicMap.containsKey(key)?dimensionDicMap.get(key):key,groupDataMap.get(key));
//                        xAxisMap.put(dimensionDicMap.containsKey(key)?dimensionDicMap.get(key): key,key);
//                    }
//                    lineNames.add(tjQuota.getName());
//                    lineData.put(tjQuota.getCode(), dataMap);
//                }
//            }
//            Map<String, Object> quotaMap = new LinkedHashMap<>();
//            ReportOption reportOption = new ReportOption();
//
//            int size = 0;
//            String quota = "";
//            if(lineData != null && lineData.size() > 0){
//                for(String key : lineData.keySet()){
//                    int tempSize = lineData.get(key).size();
//                    if (tempSize > size){
//                        size = tempSize;
//                        quota = key;
//                        quotaMap = lineData.get(key);
//                    }
//                }
//                for(String key : lineData.keySet()){
//                    List<Object> dataList = new ArrayList<>();
//                    Map<String,Object> valMap = lineData.get(key);
//                    if(key != quota){
//                        for(String name :quotaMap .keySet()){
//                            if(valMap.containsKey(name)){
//                                dataList.add(valMap.get(name));
//                            }else {
//                                dataList.add(0);
//                            }
//                        }
//                    }else{
//                        for(String name :valMap .keySet()){
//                            dataList.add(valMap.get(name));
//                        }
//                    }
//                    optionData.add(dataList);
//                }
//            }
//            Object[] xData = (Object[])quotaMap.keySet().toArray(new Object[quotaMap.size()]);
//            option = reportOption.getLineEchartOptionMoreChart(title, "", "", xData, optionData, lineNames,charTypes);
//            chartInfoModel.setOption(option.toString());
//            chartInfoModel.setTitle(title);
//            chartInfoModel.setxAxisMap(xAxisMap);
//            return chartInfoModel;
//        } catch (Exception e) {
//            error(e);
//            invalidUserException(e, -1, "查询失败:" + e.getMessage());
//            return null;
//        }
//    }
    @ApiOperation(value = "指标统计分组查询")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaGroupBy, method = RequestMethod.GET)
    public Envelop getQuotaGroupBy(
            @ApiParam(name = "id", value = "指标任务ID", required = true)
            @RequestParam(value = "id", required = true) Long id,
            @ApiParam(name = "filters", value = "检索条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension
    ) {
        Envelop envelop = new Envelop();
        try {
            TjQuota tjQuota = quotaService.findOne(id);
            Map<String, Integer>  resultMap = quotaService.searcherSumByGroupBySql(tjQuota,dimension, filters,"result","","");
            return ObjEnvelop.getSuccess("查询成功",resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
    private String getQuotaDimensionDictSql(String quotaCode, String dimension) {
        String dictSql = "";
        //查询维度
        List<TjQuotaDimensionMain> dimensionMains = tjDimensionMainService.findTjQuotaDimensionMainByQuotaCode(quotaCode);
        if (dimensionMains != null && dimensionMains.size() > 0) {
            for (TjQuotaDimensionMain main : dimensionMains) {
                if (main.getMainCode().equals(dimension)) {
                    dictSql = main.getDictSql();
                }
            }
        }
        if (StringUtils.isEmpty(dictSql)) {
            List<TjQuotaDimensionSlave> dimensionSlaves = tjDimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(quotaCode);
            if (dimensionSlaves != null && dimensionSlaves.size() > 0) {
                int slave = Integer.valueOf(dimension.substring(dimension.length() - 1, dimension.length()));
                if (dimensionSlaves.size() >= slave) {
                    dictSql = dimensionSlaves.get(slave - 1).getDictSql();
                }
            }
        }
        return dictSql;
    }
    @ApiOperation(value = "获取指标统计结果echart radar雷达图表")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaRadarGraphicReportPreviews, method = RequestMethod.GET)
    public Envelop getQuotaRadarGraphicReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr", required = true) String quotaIdStr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title) {
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        List<Integer> arrayNum = new ArrayList<>();
        Integer polorCount = 50;
        try {
            Option option = null;
            List<String> radarNames = new ArrayList<>();
            Map<String, Map<String, Object>> radarData = new HashMap<>();
            List<Map<String, Object>> listData = new ArrayList<>();
            Map<String, String> xAxisMap = new HashMap<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new HashMap<>();
                TjQuota tjQuota = quotaService.findOne(Long.valueOf(quotaId));
                if (null != tjQuota) {
                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(), dimension);
                    Map<String, String> dimensionDicMap = new HashMap<>();
                    dimensionDicMap = setDimensionMap(dictSql, dimension, dimensionDicMap);
                    //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
                    Map<String, Integer> groupDataMap = quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter, "result", "", "");
                    for (String key : groupDataMap.keySet()) {
                        key = key.toLowerCase();
                        dataMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, groupDataMap.get(key));
                        xAxisMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, key);
                    }
                    radarNames.add(tjQuota.getName());
                    radarData.put(tjQuota.getCode(), dataMap);
                }
                Integer num = getNum(dataMap);
                arrayNum.add(num);
                Map<String, Object> map = new HashMap();
                map.put(tjQuota.getName(), num);
                listData.add(map);
            }
            ReportOption reportOption = new ReportOption();
            Integer[] array = arrayNum.toArray(new Integer[arrayNum.size()]);
            Arrays.sort(array); // 进行升序排序
            polorCount += array[arrayNum.size() - 1];   // 雷达图极坐标
            option = reportOption.getRadarEchartOption(title, listData, polorCount);
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return ObjEnvelop.getSuccess("查询成功",chartInfoModel);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
    @ApiOperation(value = "获取指标统计结果echart NestedPie图表")
    @RequestMapping(value = ServiceApi.TJ.GetQuotaNestedPieReportPreviews, method = RequestMethod.GET)
    public Envelop getQuotaNestedPieGraphicReports(
            @ApiParam(name = "resourceId", value = "资源ID", defaultValue = "")
            @RequestParam(value = "resourceId") String resourceId,
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr", required = true) String quotaIdStr,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title) {
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        Option option = null;
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        Map<String, String> xAxisMap = new HashMap<>();
        try {
            Integer quotaCount = resourceQuotaService.getQuotaCount(resourceId);
            // 获取最顶层的资源
            List<Integer> quotaId = new ArrayList<>();
            ChartDataModel chartDataModel = getChartDataModel(quotaId, quotaCount, resourceId, dimension, filter, xAxisMap);
            ReportOption reportOption = new ReportOption();
            option = reportOption.getNestedPieEchartOption(title, chartDataModel);
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return ObjEnvelop.getSuccess("查询成功",chartInfoModel);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("查询失败");
        }
    }
    private ChartDataModel getChartDataModel(List<Integer> quotaId, Integer count, String resourceId, String dimension, String filter, Map<String, String> xAxisMap) throws Exception {
        ChartDataModel chartDataModel = new ChartDataModel();
        List<RsResourceQuota> resultList = resourceQuotaService.getChildrenByPidList(quotaId, resourceId);
        quotaId.clear();
        for (RsResourceQuota rq : resultList) {
            quotaId.add(Integer.valueOf(rq.getQuotaId()));
        }
        count = count - resultList.size();
        if (null != resultList && resultList.size() > 0) {
            List<Map<String, Object>> list = new ArrayList<>();
            for (RsResourceQuota rq : resultList) {
                RsResourceQuota parent = rq;
                TjQuota tjQuota = quotaService.findOne(Long.valueOf(rq.getQuotaId()));
                Map<String, Object> dataMap = new HashMap<>();
                if (null != tjQuota) {
                    String dictSql = getQuotaDimensionDictSql(tjQuota.getCode(), dimension);
                    Map<String, String> dimensionDicMap = new HashMap<>();
                    dimensionDicMap = setDimensionMap(dictSql, dimension, dimensionDicMap);
                    //使用分组计算 返回结果实例: groupDataMap -> "4205000000-儿-1": 200 =>group by 三个字段
                    Map<String, Integer> groupDataMap = quotaService.searcherSumByGroupBySql(tjQuota, dimension, filter, "result", "", "");
                    for (String key : groupDataMap.keySet()) {
                        key = key.toLowerCase();
                        dataMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, groupDataMap.get(key));
                        xAxisMap.put(dimensionDicMap.containsKey(key) ? dimensionDicMap.get(key) : key, key);
                    }
                }
                Integer num = getNum(dataMap);
                List<Map<String, Object>> mapList = new ArrayList<>();
                Map<String, Object> map = new HashMap();
                map.put("NAME", tjQuota.getName());
                map.put("TOTAL", num);
                mapList.add(map);
                rq.setMapList(mapList);
                list.addAll(rq.getMapList());
            }
            chartDataModel.setList(list);
        }
        if (count > 0) {
            ChartDataModel chartDataModel2 = getChartDataModel(quotaId, count, resourceId, dimension, filter, xAxisMap);
            if (null != chartDataModel2) {
                chartDataModel.setChildren(chartDataModel2);
            }
        }
        return chartDataModel;
    }
    private Map<String, String> setDimensionMap(String dictSql, String dimension, Map<String, String> dimensionDicMap) {
        if (StringUtils.isNotEmpty(dictSql)) {
            BasesicUtil baseUtil = new BasesicUtil();
            if (dimension.contains("slaveKey")) {
                //查询字典数据
                List<DictModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel dictModel : dictDatas) {
                    String name = baseUtil.getFieldValueByName("name", dictModel);
                    String val = baseUtil.getFieldValueByName("code", dictModel).toLowerCase();
                    dimensionDicMap.put(val, name);
                }
            } else {
                List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
                if (dictDatas != null) {
                    for (SaveModel saveModel : dictDatas) {
                        String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
                        String val = baseUtil.getFieldValueByName(dimension, saveModel).toLowerCase();
                        dimensionDicMap.put(val, name);
                    }
                }
            }
        }
        return dimensionDicMap;
    }
    private Integer getNum(Map<String, Object> dataMap) {
        Integer num = 0;
        for (String key : dataMap.keySet()) {
            Integer result = null != dataMap.get(key) ? Integer.parseInt(dataMap.get(key).toString()) : 0;
            num += result;
        }
        return num;
    }
    @RequestMapping(value = "/tj/getCostAndNumOfOutPatient", method = RequestMethod.GET)
    @ApiOperation(value = "门急诊费用、人次")
    public Map<String, String> getCostOfOutPatient() {
        Map<String, String> map = new HashMap<>();
        String costOfOutPatient = baseStatistsService.getCostOfOutPatient();
        String numOfOutPatient = baseStatistsService.getNumOfOutPatient();
        map.put("costOfOutPatient", costOfOutPatient);
        map.put("numOfOutPatient", numOfOutPatient);
        return map;
    }
    @RequestMapping(value = "/tj/getCostAndNumOfInPatient", method = RequestMethod.GET)
    @ApiOperation(value = "入院费用、人次")
    public Map<String, String> getNumOfOutPatient() {
        Map<String, String> map = new HashMap<>();
        String costOfInPatient = baseStatistsService.getCostOfInPatient();
        String numOfInPatient = baseStatistsService.getNumOfInPatient();
        map.put("costOfInPatient", costOfInPatient);
        map.put("numOfInPatient", numOfInPatient);
        return map;
    }
    @RequestMapping(value = "/tj/getMedicalMonitorInfo", method = RequestMethod.GET)
    @ApiOperation(value = "医改监测信息")
    public Map<String, String> getMedicalMonitorInfo() {
        Map<String, String> map = new HashMap<>();
        String costOfMedicalMonitor = baseStatistsService.getCostOfMedicalMonitor();
        map.put("costOfMedicalMonitor", costOfMedicalMonitor);
        return map;
    }
    @ApiOperation(value = "首页费用组成")
    @RequestMapping(value = ServiceApi.TJ.GetCostComposeReports, method = RequestMethod.GET)
    public Envelop getCostComposeReports(
            @ApiParam(name = "quotaIdStr", value = "指标ID,多个用,拼接", required = true)
            @RequestParam(value = "quotaIdStr" , required = true) String quotaIdStr,
            @ApiParam(name = "charType", value = "图表类型用", defaultValue = "1")
            @RequestParam(value = "charType", required = true) String charType,
            @ApiParam(name = "filter", value = "过滤", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "dimension", value = "维度字段", defaultValue = "quotaDate")
            @RequestParam(value = "dimension", required = false) String dimension,
            @ApiParam(name = "title", value = "视图名称", defaultValue = "")
            @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "top", value = "获取前几条数据")
            @RequestParam(value = "top", required = false) String top
    ) {
        List<String> quotaIds = Arrays.asList(quotaIdStr.split(","));
        MChartInfoModel chartInfoModel = new MChartInfoModel();
        String dimensionName = dimension + "Name";
        if ("quotaName".equals(dimension)) {
            dimensionName = "quotaName";
        }
        try {
            Option option = null;
            List<String> lineNames = new ArrayList<>();
            Map<String, Map<String, Object>> lineData = new LinkedHashMap<>();
            Map<String, String> xAxisMap = new LinkedHashMap<>();
            Integer i = 0;
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (String quotaId : quotaIds) {
                Map<String, Object> dataMap = new LinkedHashMap<>();
                TjQuota tjQuota = quotaService.findOne(Long.valueOf(quotaId));
                if (tjQuota != null) {
                    List<Map<String, Object>> resultListMap = baseStatistsService.getSimpleQuotaReport(tjQuota.getCode(), filter, dimension,true, top);
                    if (resultListMap != null && resultListMap.size() > 0) {
                        for (Map<String, Object> map : resultListMap) {
                            if (map != null && map.size() > 0) {
                                if (map.containsKey("quotaName")) {
                                    map.put("quotaName",tjQuota.getName());
                                }
                                //第一种 ES库中有定义的维度 如org,slaveKey1
                                //第二种 ES库中未定义的维度 如level,economic
                                if (map.containsKey(dimensionName)) {
                                    if(map.get(dimensionName) != null){
                                        dataMap.put(map.get(dimensionName).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimensionName).toString(), map.get(dimension).toString());
                                    }
                                } else {
                                    if(map.get(dimension) != null){
                                        dataMap.put(map.get(dimension).toString(), map.get("result"));
                                        xAxisMap.put(map.get(dimension).toString(), map.get(dimension).toString());
                                    }
                                }
                            }
                        }
                    }
                }
                lineData.put("" + i, dataMap);
                lineNames.add(tjQuota.getName());
                i++;
            }
            Set<String> hashSet = new HashSet<>(lineNames);
            Map<String, Object> newMap = new HashMap<>();
            for (Map<String, Object> data : lineData.values()) {
                for (Map.Entry<String, Object> lastMap : data.entrySet()) {
                    if (newMap.containsKey(lastMap.getKey())) {
                        double v = Double.parseDouble(newMap.get(lastMap.getKey()) + "") + Double.parseDouble(lastMap.getValue() + "");
                        newMap.put(lastMap.getKey() + "", basesicUtil.decimalPointHandle(v));
                    } else {
                        newMap.put(lastMap.getKey(), lastMap.getValue());
                    }
                    hashSet.add(lastMap.getKey());
                }
            }
            lineNames.clear();
            lineNames.addAll(hashSet);
            lineData.clear();
            for (int j = 0; j < lineNames.size(); j++) {
                String name = lineNames.get(j);
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put(name, newMap.get(name));
                lineData.put("" + j, tempMap);
                Map<String, Object> listMapCon = new HashMap<>();
                listMapCon.put("quotaName", name);
                listMapCon.put("result", newMap.get(name));
                listMap.add(listMapCon);
            }
            ReportOption reportOption = new ReportOption();
            if (charType.equals("common")) {
                charType = "1";
            } else if (charType.equals("twoDimensional")) {
                return null;
            }
            List<String> charTypes = Arrays.asList(charType);
            int type = Integer.valueOf(charType);
            if (type == ReportOption.bar) {
                return null;    // 尚未拓展
            } else if (type == ReportOption.line) {
                return null;    // 尚未拓展
            } else if (type == ReportOption.pie) {
                List<Map<String, Object>> datalist = new ArrayList<>();
                for (Map<String, Object> resultMap : listMap) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("NAME", null == resultMap.get(dimensionName) ? resultMap.get(dimension) : resultMap.get(dimensionName));
                    map.put("TOTAL", resultMap.get("result"));
                    if(resultMap.get(dimensionName) != null){
                        map.put("NAME",resultMap.get(dimensionName));
                    }else {
                        //非 指标中配置的维度 关联出来的字段
                        if(dimensionName.equals("levelName")){
                            if(resultMap.get(dimension).equals("1")){
                                map.put("NAME","一级医院");
                            }else  if(resultMap.get(dimension).equals("2")){
                                map.put("NAME","二级医院");
                            }else  if(resultMap.get(dimension).equals("3")){
                                map.put("NAME","三级医院");
                            }
                        }
                    }
                    map.put("TOTAL",resultMap.get("result"));
                    datalist.add(map);
                }
                option = reportOption.getPieEchartOption(title, "", "", datalist, lineNames.get(0), null);
            }
            chartInfoModel.setOption(option.toString());
            chartInfoModel.setTitle(title);
            chartInfoModel.setxAxisMap(xAxisMap);
            return ObjEnvelop.getSuccess("查询成功",chartInfoModel);
        } catch (Exception e) {
            return failed("查询失败");
        }
    }
    @RequestMapping(value = ServiceApi.TJ.GetDeviceReports, method = RequestMethod.GET)
    @ApiOperation(value = "报表-卫生设备一览")
    public Envelop getDeviceReports(
            @ApiParam(name = "year", value = "年份", required = true)
            @RequestParam(value = "year" , required = true) String year,
            @ApiParam(name = "district", value = "区县编码")
            @RequestParam(value = "district", required = false) String district,
            @ApiParam(name = "organization", value = "机构名称或者组织机构代码", defaultValue = "")
            @RequestParam(value = "organization", required = false) String organization,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page) throws Exception{
        PageEnvelop envelop = new PageEnvelop();
        List<MQcDevice> list = new ArrayList<>();
        List<Map<String, Object>> dataList = deviceService.listMQcDeviceByYearAndDistrictAndOrg(year,district,organization,page ,size);
        for(int i=0; i<dataList.size(); i++){
            Map<String,Object> dataMap =dataList.get(i);
            MQcDevice newEntity = objectMapper.readValue(toJson(dataMap), MQcDevice.class);
            list.add(newEntity);
        }
        envelop.setDetailModelList(list);
        envelop.setStatus(200);
        envelop.setPageSize(size);
        envelop.setCurrPage(page);
//        envelop.setTotalPage((int)dataList.getPage());
//        envelop.setTotalCount((int)dataList.getCount());
        return envelop;
    }
    protected String toJson(Object obj) throws JsonProcessingException {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        return objectMapper.writeValueAsString(obj);
    }
    /**
     * 如果有计量单位,则把数值换算成相应的数值单位
     * @param optionData
     * @param dataMeasurement
     * @return
     */
    public List<List<Object>> discountByMeasurement(List<List<Object>> optionData, String dataMeasurement) {
        if (!StringUtils.isEmpty(dataMeasurement)) {
            List<List<Object>> handleList = new ArrayList<>();
            double v = Double.parseDouble(dataMeasurement);
            optionData.forEach(one -> {
                List<Object> list = new ArrayList<>();
                one.forEach(item -> {
                    if(item != null && !item.toString().equals("--")){
                        item = basesicUtil.decimalPointHandle(Double.parseDouble(item.toString()) / v);
                        list.add(item);
                    }else {
                        list.add(0);
                    }
                });
                handleList.add(list);
            });
            return handleList;
        }
        return optionData;
    }
}

+ 1 - 2
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjDataSaveEndPoint.java

@ -28,8 +28,7 @@ import java.util.List;
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "TjDataSave", description = "数据存储", tags = {"统计指标管理-数据存储"})
public class TjDataSaveEndPoint extends EnvelopRestEndpoint {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    TjDataSaveService tjDataSaveService;

+ 2 - 5
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjDimensionMainEndPoint.java

@ -29,9 +29,6 @@ import java.util.List;
@Api(value = "TjDimensionMain", description = "主维度", tags = {"主维度"})
public class TjDimensionMainEndPoint extends EnvelopRestEndpoint {
    @Autowired
    ObjectMapper objectMapper;
    
    @Autowired
    TjDimensionMainService tjDimensionMainService;
@ -88,7 +85,7 @@ public class TjDimensionMainEndPoint extends EnvelopRestEndpoint {
    public Envelop delete(
            @ApiParam(name = "id", value = "编号", defaultValue = "")
            @RequestParam(value = "id") Long id) throws Exception{
        TjDimensionMain tjDimensionMain = tjDimensionMainService.getTjDimensionMain(Integer.valueOf(id.toString()));
        TjDimensionMain tjDimensionMain = tjDimensionMainService.getTjDimensionMain(id);
        tjDimensionMain.setStatus(-1);
        tjDimensionMainService.save(tjDimensionMain);
        return ObjEnvelop.getSuccess("主维度删除成功!");
@ -97,7 +94,7 @@ public class TjDimensionMainEndPoint extends EnvelopRestEndpoint {
    @RequestMapping(value = ServiceApi.TJ.TjDimensionMainId, method = RequestMethod.GET)
    @ApiOperation(value = "获取主维度信息", notes = "获取主维度信息")
    TjDimensionMain getTjDimensionMain(
            @PathVariable(value = "id") Integer id){
            @PathVariable(value = "id") Long id){
        return tjDimensionMainService.getTjDimensionMain(id);
    };

+ 1 - 1
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/controller/TjQuotaCategoryEndPoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.basic.quota.controller;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.jw.basic.quota.service.TjQuotaCategoryService;
import com.yihu.jw.basic.quota.service.TjQuotaService;
import com.yihu.jw.entity.ehr.quota.TjQuotaCategory;
@ -8,7 +9,6 @@ import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.rm.svrBasic.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

+ 18 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/dao/TjQuotaGovProvisionDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.basic.quota.dao;
import com.yihu.jw.entity.ehr.quota.TjQuotaGovProvision;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
 * Created by wxw on 2018/3/6.
 */
public interface TjQuotaGovProvisionDao extends JpaRepository<TjQuotaGovProvision, Long> {
    @Query("select sum(gp.population) from TjQuotaGovProvision gp where gp.administrativeDivision = :town and gp.year = :year ")
    Long getSumByDistrict(@Param("town") long town, @Param("year") String year);
    @Query("select sum(gp.population) from TjQuotaGovProvision gp where  gp.year = :year ")
    Long getSumByDistrict(@Param("year") String year);
}

+ 387 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/model/SaveModel.java

@ -0,0 +1,387 @@
package com.yihu.jw.basic.quota.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.searchbox.annotations.JestId;
import org.springframework.data.annotation.CreatedDate;
import java.util.Date;
/**
 * Created by chenweida on 2017/6/1.
 */
public class SaveModel {
    @JestId
    private String id;
    private String saasId;//saasId
    private String quotaCode;//指标code
    private String quotaName;//指标名称
    private String quotaDate;//统计的指标对应时间 如今天凌晨统计昨天的数据,那就是昨天的时间
    private String org;     //机构代码
    private String orgName;//机构名字
    private String province;//省级代码 350000
    private String provinceName;//省名字
    private String city;//城市代码 350200
    private String cityName;//
    private String town;//区代码 350206
    private String townName;//
    private String dept;//科室的code
    private String deptName;//
    private String slaveKey1;//从维度  1级维度
    private String slaveKey1Name;
    private String slaveKey2;//从维度  2级维度
    private String slaveKey2Name;
    private String slaveKey3;//从维度  3级维度
    private String slaveKey3Name;
    private String slaveKey4;//从维度  4级维度
    private String slaveKey4Name;
    private String result;//统计结果
    private String timeLevel;// 1 日 2 周 3 月 4 年
    private String areaLevel;// 1 省 2 市 3 区县 4 机构 5团队
    private String year;
    private String yearName;
    private String orgHealthCategoryCode;     //卫生机构类型代码
    private String orgHealthCategoryName;   //卫生机构类型名字
    private String orgHealthCategoryId;
    private String orgHealthCategoryPid;
    private String orgHealthCategoryTopPid;
    private String economic;    // 经济类型代码
    private String economicName;    // 经济类型名称
    private String level;   // 医院等级
    private String levelName;   // 医院等级名称
    private String distinctField;   // 去重字段
    private String distinctFieldValue;   // 去重字段值
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")// 2017-06-24T11:51:30+080
    @CreatedDate
    private Date createTime;//创建时间
    private Date createDate;//档案入库时间
    public String getQuotaDate() {
        return quotaDate;
    }
    public void setQuotaDate(String quotaDate) {
        this.quotaDate = quotaDate;
    }
    public String getOrg() {
        return org;
    }
    public void setOrg(String org) {
        this.org = org;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    public String getSlaveKey1() {
        return slaveKey1;
    }
    public void setSlaveKey1(String slaveKey1) {
        this.slaveKey1 = slaveKey1;
    }
    public String getSlaveKey2() {
        return slaveKey2;
    }
    public void setSlaveKey2(String slaveKey2) {
        this.slaveKey2 = slaveKey2;
    }
    public String getSlaveKey3() {
        return slaveKey3;
    }
    public void setSlaveKey3(String slaveKey3) {
        this.slaveKey3 = slaveKey3;
    }
    public String getSlaveKey4() {
        return slaveKey4;
    }
    public void setSlaveKey4(String slaveKey4) {
        this.slaveKey4 = slaveKey4;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String getSlaveKey1Name() {
        return slaveKey1Name;
    }
    public void setSlaveKey1Name(String slaveKey1Name) {
        this.slaveKey1Name = slaveKey1Name;
    }
    public String getSlaveKey2Name() {
        return slaveKey2Name;
    }
    public void setSlaveKey2Name(String slaveKey2Name) {
        this.slaveKey2Name = slaveKey2Name;
    }
    public String getSlaveKey3Name() {
        return slaveKey3Name;
    }
    public void setSlaveKey3Name(String slaveKey3Name) {
        this.slaveKey3Name = slaveKey3Name;
    }
    public String getSlaveKey4Name() {
        return slaveKey4Name;
    }
    public void setSlaveKey4Name(String slaveKey4Name) {
        this.slaveKey4Name = slaveKey4Name;
    }
    public String getProvinceName() {
        return provinceName;
    }
    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode.replaceAll("_","");
    }
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
    public String getAreaLevel() {
        return areaLevel;
    }
    public void setAreaLevel(String areaLevel) {
        this.areaLevel = areaLevel;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getQuotaName() {
        return quotaName;
    }
    public void setQuotaName(String quotaName) {
        this.quotaName = quotaName;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getYearName() {
        return yearName;
    }
    public void setYearName(String yearName) {
        this.yearName = yearName;
    }
    public String getOrgHealthCategoryCode() {
        return orgHealthCategoryCode;
    }
    public void setOrgHealthCategoryCode(String orgHealthCategoryCode) {
        this.orgHealthCategoryCode = orgHealthCategoryCode;
    }
    public String getOrgHealthCategoryName() {
        return orgHealthCategoryName;
    }
    public void setOrgHealthCategoryName(String orgHealthCategoryName) {
        this.orgHealthCategoryName = orgHealthCategoryName;
    }
    public String getOrgHealthCategoryId() {
        return orgHealthCategoryId;
    }
    public void setOrgHealthCategoryId(String orgHealthCategoryId) {
        this.orgHealthCategoryId = orgHealthCategoryId;
    }
    public String getOrgHealthCategoryPid() {
        return orgHealthCategoryPid;
    }
    public void setOrgHealthCategoryPid(String orgHealthCategoryPid) {
        this.orgHealthCategoryPid = orgHealthCategoryPid;
    }
    public String getEconomic() {
        return economic;
    }
    public void setEconomic(String economic) {
        this.economic = economic;
    }
    public String getEconomicName() {
        return economicName;
    }
    public void setEconomicName(String economicName) {
        this.economicName = economicName;
    }
    public String getLevel() {
        return level;
    }
    public void setLevel(String level) {
        this.level = level;
    }
    public String getLevelName() {
        return levelName;
    }
    public void setLevelName(String levelName) {
        this.levelName = levelName;
    }
    public String getOrgHealthCategoryTopPid() {
        return orgHealthCategoryTopPid;
    }
    public void setOrgHealthCategoryTopPid(String orgHealthCategoryTopPid) {
        this.orgHealthCategoryTopPid = orgHealthCategoryTopPid;
    }
    public String getDistinctField() {
        return distinctField;
    }
    public void setDistinctField(String distinctField) {
        this.distinctField = distinctField;
    }
    public String getDistinctFieldValue() {
        return distinctFieldValue;
    }
    public void setDistinctFieldValue(String distinctFieldValue) {
        this.distinctFieldValue = distinctFieldValue;
    }
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

+ 2001 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/BaseStatistsService.java

@ -0,0 +1,2001 @@
package com.yihu.jw.basic.quota.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.es.EsResultExtract;
import com.yihu.jw.basic.es.util.ElasticsearchUtil;
import com.yihu.jw.basic.quota.dao.TjQuotaGovProvisionDao;
import com.yihu.jw.basic.quota.dao.XTjQuotaRepository;
import com.yihu.jw.basic.util.BasesicUtil;
import com.yihu.jw.entity.ehr.quota.*;
import com.yihu.jw.restmodel.ehr.quota.EsConfig;
import com.yihu.jw.restmodel.ehr.tj.DictModel;
import com.yihu.jw.restmodel.ehr.tj.SaveModel;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.util.date.DateUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by janseny on 2018/01/15.
 */
@Service
public class BaseStatistsService {
    Logger log = LoggerFactory.getLogger(BaseStatistsService.class);
    @Autowired
    private XTjQuotaRepository quotaDao;
    @Autowired
    private EsResultExtract esResultExtract;
    @Autowired
    private TjDimensionMainService tjDimensionMainService;
    @Autowired
    private TjDimensionSlaveService tjDimensionSlaveService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private OrgHealthCategoryStatisticsService orgHealthCategoryStatisticsService;
    @Autowired
    private TjDataSourceService dataSourceService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private SingleDiseaseService singleDiseaseService;
    @Autowired
    private TjQuotaGovProvisionDao tjQuotaGovProvisionDao;
    @Autowired
    private TjDataSaveService dataSaveService;
    private BasesicUtil basesicUtil = new BasesicUtil();
    private static String orgHealthCategory = "orgHealthCategory";
    public static String orgHealthCategoryCode = "orgHealthCategoryCode";
    public static String resultField = "result";
    public static String quotaDateField = "quotaDate";
    public static String firstColumnField = "firstColumn";
    /**
     *  特殊机构类型   根据 上级基础指标code 获取基础数据集
     * @param code
     * @param filter
     * @param dimension
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getOrgHealthCategoryQuotaResultList(String code,String dimension,String filter, String top) throws Exception {
        List<Map<String, Object>> dimenListResult = getOrgHealthCategoryAggregationResult(code, dimension, filter, top);
        return dimenListResult;
    }
    /**
     * 根据指标code 和维度及条件 分组获取指标查询结果集
     * @param code
     * @param filter
     * @param dimension
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getQuotaResultList(String code,String dimension,String filter,String dateType, String top) throws Exception {
        code = getBasicQuota(code);
        List<Map<String, Object>> dimenListResult = new ArrayList<>();
        if(StringUtils.isNotEmpty(dateType)){
            dimenListResult = getTimeAggregationResult(code, dimension, filter, dateType);
        }else {
            dimenListResult = getAggregationResult(code, dimension, filter, top);
        }
        return dimenListResult;
    }
    /**
     * 查找指标的最底层指标code
     * @param quotaCode
     * @return
     */
    public String getBasicQuota(String quotaCode){
        String code = quotaCode;
        TjQuota tjQuota = quotaService.findByCode(quotaCode);
        if( tjQuota != null && StringUtils.isNotEmpty(tjQuota.getResultGetType())){
            if (tjQuota.getResultGetType().equals("2")){//二次统计
                TjQuotaDataSource quotaDataSorce = dataSourceService.findSourceByQuotaCode(quotaCode);
                if(quotaDataSorce != null){
                    JSONObject obj = new JSONObject().fromObject(quotaDataSorce.getConfigJson());
                    EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
                    if(StringUtils.isNotEmpty(esConfig.getSuperiorBaseQuotaCode()) && StringUtils.isEmpty(esConfig.getEspecialType()) ){
                        code =  esConfig.getSuperiorBaseQuotaCode();
                    }
                }
            }
        }
        return code;
    }
    public List<Map<String, Object>>  addQuota(String addFirstQuotaCode,String firstFilter, String addSecondQuotaCode, String secondFilter,String operation ,String dimension,String dateType, String top) throws Exception {
        List<Map<String, Object>> firstList = getQuotaResultList(addFirstQuotaCode,dimension,firstFilter,dateType, top);
        List<Map<String, Object>> secondList =  getQuotaResultList(addSecondQuotaCode,dimension,secondFilter,dateType, top);
        dimension = StringUtils.isNotEmpty(dateType)? (StringUtils.isNotEmpty(dimension)? dimension +";"+dateType : dateType):dimension;
        List<Map<String, Object>> addition = addition(dimension, firstList, secondList, Integer.valueOf(operation));
        if (StringUtils.isNotEmpty(top)) {
            addition = sortResultList(addition, top);
        }
        return addition;
    }
    public List<Map<String, Object>> addition(String dimension, List<Map<String, Object>> firstList, List<Map<String, Object>> secondList,int operation){
        List<Map<String, Object>> addResultList = new ArrayList<>();
        List<Map<String, Object>> otherList = new ArrayList<>();
        otherList = secondList;
        String [] moleDimensions = dimension.split(";");
        for(Map<String, Object> firstMap :firstList) {
            if (null != firstMap && firstMap.size() > 0 ) {
                Map<String, Object> map = new HashMap<>();
                double firstResultVal = Double.valueOf(firstMap.get("result") == null ? "0" : firstMap.get(resultField).toString());
                map.put(firstColumnField, firstMap.get(firstColumnField));
                String firstKeyVal = "";
                for(int i = 0 ;i < moleDimensions.length ; i++){
                    if(i == 0){
                        firstKeyVal = firstMap.get(moleDimensions[i]).toString();
                    }else {
                        firstKeyVal = firstKeyVal + "-" + firstMap.get(moleDimensions[i]).toString() ;
                    }
                    map.put(moleDimensions[i], firstMap.get(moleDimensions[i]).toString());
                    if(moleDimensions[i].equals("town") || moleDimensions[i].equals("org") ){
                        if(firstMap.get(moleDimensions[i] + "Code")  != null){
                            map.put(moleDimensions[i]+ "Code", firstMap.get(moleDimensions[i] + "Code").toString());
                        }
                    }
                }
                boolean pflag = true;
                for(Map<String, Object> secondMap :secondList) {
                    String secondKeyVal = "";
                    String [] dimeDimensions = dimension.split(";");
                    for(int i = 0 ;i < dimeDimensions.length ; i++){
                        if(i == 0){
                            secondKeyVal = secondMap.get(dimeDimensions[i]).toString();
                        }else {
                            secondKeyVal = secondKeyVal + "-" + secondMap.get(dimeDimensions[i]).toString() ;
                        }
                    }
                    if(firstKeyVal.equals(secondKeyVal) || "quotaName".equals(dimension)){  // 如果维度是quotaName,则进入逻辑
                        double point = 0;
                        double dimeResultVal = Double.valueOf(secondMap.get(resultField).toString());
                        BigDecimal first = new BigDecimal(Double.toString(firstResultVal));
                        BigDecimal second = new BigDecimal(Double.toString(dimeResultVal));
                        if(operation == 1){ //1 加法 默认
                            point = first.add(second).doubleValue();
                        }else if(operation == 2){ //2 减法
                            point = first.subtract(second).doubleValue();
                        }
                        map.put(resultField, basesicUtil.decimalPointHandle(point));
                        addResultList.add(map);
                        pflag = false;
                        otherList.remove(secondMap);
                        break;
                    }
                }
                if(pflag){
                    map.put(resultField, basesicUtil.decimalPointHandle(firstResultVal));
                    addResultList.add(map);
                }
            }
        }
        if (null != otherList && otherList.size() > 0) {
            for(Map<String, Object> secondMap : otherList) {
                Map<String, Object> map = new HashMap<>();
                map.put(firstColumnField, secondMap.get(firstColumnField));
                for(int i = 0 ;i < moleDimensions.length ; i++){
                    map.put(moleDimensions[i], secondMap.get(moleDimensions[i]).toString());
                    if((moleDimensions[i].equals("town") || moleDimensions[i].equals("org")) && null != secondMap.get(moleDimensions[i] + "Code")) {
                        map.put(moleDimensions[i] + "Code", secondMap.get(moleDimensions[i] + "Code").toString());
                    }
                }
                double point = 0;
                double secondResultVal = Double.valueOf(secondMap.get("result") == null ? "0" : secondMap.get(resultField).toString());
                if (secondResultVal != 0) {
                    if(operation == 1){ //1 加法 默认
                        point = secondResultVal ;
                    }else if(operation == 2){ //2 减法
                        point = -secondResultVal;
                    }
                }
                map.put(resultField, basesicUtil.decimalPointHandle(point));
                addResultList.add(map);
            }
        }
        //检查后面指标的维度是否全部有 累加进去
        /*Map<String, Object> addResuDimenMap = new HashMap<>();
        for(int k = 0;k < addResultList.size();k++) {
            Map<String, Object> addResultMap = addResultList.get(k);
            String addDimenStr = "";
            for (int i = 0; i < moleDimensions.length; i++) {
                addDimenStr += addResultMap.get(moleDimensions[i]).toString() + "-";
            }
            addResuDimenMap.put(addDimenStr,addDimenStr);
        }
        for(Map<String, Object> secondMap :secondList) {
            String secondDimenStr = "";
            String addDimenStr = "";
            for(int i = 0 ;i < moleDimensions.length ; i++){
                secondDimenStr +=  secondMap.get(moleDimensions[i]).toString() + "-";
            }
            if( !addResuDimenMap.containsKey(secondDimenStr)){
                if( !addDimenStr.equals(secondDimenStr)){
                    Map<String, Object> map = new HashMap<>();
                    float dimeResultVal = Float.valueOf(secondMap.get(resultField).toString());
                    map.put(resultField,df.format(dimeResultVal));
                    map.put(firstColumnField, secondMap.get(firstColumnField));
                    for(int i = 0 ;i < moleDimensions.length ; i++){
                        map.put(moleDimensions[i], secondMap.get(moleDimensions[i]).toString());
                    }
                    addResultList.add(map);
                }
            }
        }*/
        if (moleDimensions.length == 1 && "month".equalsIgnoreCase(moleDimensions[0])) {
            addResultList = sortResultListByMonth(addResultList);
        }
        return  addResultList;
    }
    public List<Map<String, Object>> sortResultList(List<Map<String, Object>> listMap, String top) {
        if (null != listMap && listMap.size() > 0) {
            Collections.sort(listMap, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    // 根据result进行降序
                    double result = Double.parseDouble(o1.get("result") + "");
                    double result2 = Double.parseDouble(o2.get("result") + "");
                    double v = result2 - result;
                    return v > 0 ? 1 : v == 0 ? 0 : -1;
                }
            });
            if (StringUtils.isNotEmpty(top)) {
                int t = Integer.parseInt(top);
                listMap = listMap.subList(0, listMap.size() > t ? t :listMap.size());
            }
        }
        return listMap;
    }
    public static List<Map<String, Object>> sortResultListByMonth(List<Map<String, Object>> listMap) {
        if (null != listMap && listMap.size() > 0) {
            Collections.sort(listMap, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    // 根据month进行升序
                    String month1 = o1.get("month") + "";
                    String month2 = o2.get("month") + "";
                    int v = month1.compareTo(month2);
                    return v > 0 ? 1 : v == 0 ? 0 : -1;
                }
            });
        }
        return listMap;
    }
    /**
     * 两个维度相同指标除法运算
     * @param molecular
     * @param denominator
     * @param dimension
     * @param molecularFilter
     * @param denominatorFilters
     * @param operation
     * @param operationValue
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>>  divisionQuota(String molecular, String denominator, String dimension,
        String molecularFilter,String denominatorFilters,String operation,String operationValue,String dateType, String top) throws Exception {
        if(StringUtils.isEmpty(dimension) && StringUtils.isNotEmpty(dateType)){
            dimension = dateType;
        }
        List<Map<String, Object>> moleList = getSimpleQuotaReport(molecular, molecularFilter,dimension ,false , top);
        List<Map<String, Object>> denoList =  getSimpleQuotaReport(denominator,denominatorFilters,dimension,false, null);
        dimension = StringUtils.isNotEmpty(dateType)? (StringUtils.isNotEmpty(dimension)? dimension +";"+dateType : dateType):dimension;
       return division(dimension,moleList,denoList,Integer.valueOf(operation),Integer.valueOf(operationValue));
    }
    /**
     * 指标除法运算 分母按年份获取总数
     * @param molecular 分子
     * @param dimension 分母
     * @param molecularFilter 分子条件
     * @param denominatorFilter 分母条件
     * @param operation
     * @param operationValue
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> divisionQuotaDenoConstant(String molecular, String dimension,String molecularFilter,String denominatorFilter,
        String operation,String operationValue,String dateType , String top) throws Exception {
        Double denominatorVal = 0.0;
        List<Map<String, Object>> moleList = getQuotaResultList(molecular,dimension,molecularFilter,dateType, top);
        String year = DateUtil.getYearFromYMD(new Date());
        String town = "";
        if(StringUtils.isNotEmpty(denominatorFilter)){
            String [] filter = denominatorFilter.split("and");
            if(filter.length > 0 ){
                for(String key : filter){
                    if(key.contains(quotaDateField)){
                        year = key.substring(key.indexOf("'")+1,key.indexOf("'")+5);//quotaDate >= '2018-03-01'
                    }
                    if(key.contains("town")){
                        town =  key.substring(key.indexOf("=")+1);
                    }
                }
            }
        }
        Long sumValue = null;
        if(StringUtils.isNotEmpty(town)){
            sumValue = tjQuotaGovProvisionDao.getSumByDistrict(Long.parseLong(town),year);
       }else {
            sumValue = tjQuotaGovProvisionDao.getSumByDistrict(year);
       }
        // 获取分母的数值
        if(sumValue != null && sumValue.doubleValue() != 0){
            denominatorVal = sumValue.doubleValue();
            return divisionDenoConstant(dimension, moleList, denominatorVal, Integer.valueOf(operation), Integer.valueOf(operationValue));
        }else {
            return  null;
        }
    }
    /**
     * 指标结果相除
     * 除法运算 分母按年份获取总数
     * @param dimension 维度
     * @param moleList 分子
     * @param denominatorVal 分母 数值
     * @param operation 运算方式 1 乘法 2 除法
     * @param operationValue 运算参数值
     *
     */
    public List<Map<String, Object>> divisionDenoConstant(String dimension, List<Map<String, Object>> moleList, Double denominatorVal,int operation,int operationValue) {
        List<Map<String, Object>> divisionResultList = new ArrayList<>();
        for (Map<String, Object> moleMap : moleList) {
            Map<String, Object> map = new HashMap<>();
            double moleResultVal = Double.valueOf(moleMap.get(resultField).toString());
            String moleKeyVal = "";
            String [] moleDimensions = dimension.split(";");
            for(int i = 0 ;i < moleDimensions.length ; i++){
                if(i == 0){
                    moleKeyVal = moleMap.get(moleDimensions[i]).toString();
                }else {
                    moleKeyVal = moleKeyVal + "-" + moleMap.get(moleDimensions[i]).toString() ;
                }
                map.put(moleDimensions[i], moleMap.get(moleDimensions[i]).toString());
                map.put(moleDimensions[i]+"Name", moleMap.get(moleDimensions[i]).toString());
            }
            if (moleResultVal == 0) {
                map.put(resultField,0);
                divisionResultList.add(map);
            } else {
                double point = 0;
                if (operation == 1) {
                    point = (moleResultVal / denominatorVal) * operationValue;
                } else if (operation == 2) {
                    point =  (moleResultVal / denominatorVal) / operationValue;
                }
                map.put(resultField, basesicUtil.decimalPointHandle(point));
                divisionResultList.add(map);
            }
        }
        return divisionResultList;
    }
    /**
     * 指标结果相除
     * @param dimension 维度
     * @param moleList 分子
     * @param denoList 分母
     * @param operation 运算方式 1 乘法 2 除法
     * @param operationValue 运算参数值
     *
     */
    public List<Map<String, Object>> division(String dimension, List<Map<String, Object>> moleList, List<Map<String, Object>> denoList,int operation,int operationValue){
        List<Map<String, Object>> divisionResultList = new ArrayList<>();
        for(Map<String, Object> moleMap :moleList) {
            if (null != moleMap && moleMap.size() > 0 ) {
                Map<String, Object> map = new HashMap<>();
                double moleResultVal = Double.valueOf(moleMap.get(resultField) == null ? "0" : moleMap.get(resultField).toString());
                String moleKeyVal = "";
                String [] moleDimensions = dimension.split(";");
                for(int i = 0 ;i < moleDimensions.length ; i++){
                    if(i == 0){
                        moleKeyVal = moleMap.get(moleDimensions[i]).toString();
                    }else {
                        moleKeyVal = moleKeyVal + "-" + moleMap.get(moleDimensions[i]).toString() ;
                    }
                    map.put(firstColumnField, moleMap.get(firstColumnField));
                    map.put(moleDimensions[i], moleMap.get(moleDimensions[i]).toString());
                    map.put(moleDimensions[i]+"Name", moleMap.get(moleDimensions[i]).toString());
                    if("town".equals(moleDimensions[i]) || "org".equals(moleDimensions[i])) {
                        if(moleMap.get(moleDimensions[i] + "Code")  != null) {
                            map.put(moleDimensions[i]+ "Code", moleMap.get(moleDimensions[i] + "Code").toString());
                        }
                    }
                }
                if (moleResultVal == 0) {
                    map.put(resultField,0);
                    divisionResultList.add(map);
                } else {
                    for(Map<String, Object> denoMap :denoList) {
                        String dimenKeyVal = "";
                        String [] dimeDimensions = dimension.split(";");
                        for(int i = 0 ;i < dimeDimensions.length ; i++){
                            if(i == 0){
                                dimenKeyVal = denoMap.get(dimeDimensions[i]).toString();
                            }else {
                                dimenKeyVal = dimenKeyVal + "-" + denoMap.get(dimeDimensions[i]).toString() ;
                            }
                        }
                        if(moleKeyVal.equals(dimenKeyVal)){
                            double point = 0;
                            float dimeResultVal = Float.valueOf(denoMap.get(resultField).toString());
                            if(dimeResultVal != 0){
                                if(operation == 1){
                                    point = (moleResultVal/dimeResultVal) * operationValue;
                                }else if(operation == 2){
                                    point = (moleResultVal/dimeResultVal) / operationValue;
                                }
                            }
                            map.put(resultField, basesicUtil.decimalPointHandle(point));
                            divisionResultList.add(map);
                            break;
                        }
                    }
                }
            }
        }
        Double moleVal = caculateResult(moleList);
        Double denoVal = caculateResult(denoList);
        if (0 != denoVal) {
            Map<String, Object> map = new HashMap<>();
            double result = 0;
            if(operation == 1) {
                result = (moleVal / denoVal) * operationValue;
            } else if(operation == 2) {
                result = (moleVal / denoVal) / operationValue;
            }
            map.put("result", basesicUtil.decimalPointHandle(result));
            map.put("firstColumn", "合计");
            map.put(dimension, "合计");
            divisionResultList.add(map);
        }
        return  divisionResultList;
    }
    /**
     * 特殊机构类别 根据条件查询结果
     * @param code
     * @param filters
     * @param  dateType 日期类型
     * @param isTrunTree 是否转为机构类型树状机构
     * @throws Exception
     */
    public List<Map<String, Object>>  getOrgHealthCategory(String code,String filters,String dateType,boolean isTrunTree, String top) throws Exception {
        List<Map<String, Object>> dimenListResult = new ArrayList<>();
        if(dateType != null && (dateType.contains("year") || dateType.contains("quarter")|| dateType.contains("month") || dateType.contains("day"))){
            dimenListResult = getTimeAggregationResult(code,orgHealthCategoryCode,filters,dateType);//dimension 维度为 year,month,day
        }else {
            dimenListResult = getAggregationResult(code, orgHealthCategoryCode, filters, top);
        }
        if(isTrunTree){
            List<Map<String, Object>> orgHealthCategoryList = orgHealthCategoryStatisticsService.getOrgHealthCategoryTreeByPid(-1);
            List<Map<String, Object>> resultList = setResult(code,orgHealthCategoryList,dimenListResult,dateType);
            return resultList;
        }else {
            return dimenListResult;
        }
    }
    /**
     * 递归循环 查询机构类型对应的名称和父节点
     * @param orgHealthCategoryList
     * @param dimenListResult
     * @param
     * @return
     */
    public List<Map<String,Object>> setResult(String quotaCode,List<Map<String,Object>> orgHealthCategoryList,List<Map<String, Object>> dimenListResult,String dateType){
        List<Map<String,Object>> result = new ArrayList<>();
        for(int i=0 ; i < orgHealthCategoryList.size() ; i++ ){
            Map<String,Object> mapCategory = orgHealthCategoryList.get(i);
            String code = mapCategory.get("code").toString();
            boolean notExitFalg = true;
            for(Map<String, Object> dimenMap : dimenListResult){
                boolean flag = false;
                if(dimenMap.get(orgHealthCategoryCode) != null){
                    flag = dimenMap.get(orgHealthCategoryCode).equals(code);
                }
                if(dimenMap.get(code) != null || flag ){
//                    mapCategory.putAll(dimenMap);
                    if(dimenMap.containsKey(code)){
                        mapCategory.put(code,dimenMap.get(code));
                        mapCategory.put(resultField,dimenMap.get(resultField)!=null ? dimenMap.get(resultField):dimenMap.get(code));
                    }
                    if(StringUtils.isNotEmpty(dateType)){
                        mapCategory.put(dimenMap.get(dateType).toString(),dimenMap.get(resultField));
                    }
                    mapCategory.put(quotaCode,dimenMap.get(resultField));
                    break;
                }
            }
            if(notExitFalg){
                mapCategory.put(resultField,0);
                mapCategory.put(quotaCode,0);
            }
            mapCategory.put(firstColumnField,mapCategory.get("text"));
            result.add(mapCategory);
            if(mapCategory.get("children") != null){
                List<Map<String,Object>> childrenOrgHealthCategoryList = (List<Map<String, Object>>) mapCategory.get("children");
                mapCategory.put("children",setResult(quotaCode,childrenOrgHealthCategoryList,dimenListResult,dateType));
            }
        }
        return  result;
    }
//    /**
//     * 递归循环 查询机构类型对应的名称和父节点
//     * @param orgHealthCategoryList
//     * @param dimenListResult
//     * @param
//     * @return
//     */
//    public List<Map<String,Object>> setResultAllDimenMap(String quotaCode,List<Map<String,Object>> orgHealthCategoryList,List<Map<String, Object>> dimenListResult,String dateType){
//        List<Map<String,Object>> result = new ArrayList<>();
//        for(int i=0 ; i < orgHealthCategoryList.size() ; i++ ){
//            Map<String,Object> mapCategory = orgHealthCategoryList.get(i);
//            String code = mapCategory.get("code").toString();
//            boolean notExitFalg = true;
//            for(Map<String, Object> dimenMap : dimenListResult){
//                boolean flag = false;
//                if(dimenMap.get(orgHealthCategoryCode) != null){
//                    flag = dimenMap.get(orgHealthCategoryCode).equals(code);
//                }
//                if(dimenMap.get(code) != null || flag ){
//                    //补充所有信息
//                    mapCategory.putAll(dimenMap);
//                    if(dimenMap.containsKey(code)){
//                        mapCategory.put(code,dimenMap.get(code));
//                        mapCategory.put(resultField,dimenMap.get(resultField)!=null ? dimenMap.get(resultField):dimenMap.get(code));
//                    }
//                    if(StringUtils.isNotEmpty(dateType)){
//                        mapCategory.put(dimenMap.get(dateType).toString(),dimenMap.get(resultField));
//                    }
//                    mapCategory.put(quotaCode,dimenMap.get(resultField));
//                    notExitFalg = false;
//                    break;
//                }
//            }
//            if(notExitFalg){
//                mapCategory.put(resultField,0);
//                mapCategory.put(quotaCode,0);
//            }
//            mapCategory.put(firstColumnField,mapCategory.get("text"));
//            result.add(mapCategory);
//            if(mapCategory.get("children") != null){
//                List<Map<String,Object>> childrenOrgHealthCategoryList = (List<Map<String, Object>>) mapCategory.get("children");
//                mapCategory.put("children",setResultAllDimenMap(quotaCode, childrenOrgHealthCategoryList, dimenListResult, dateType));
//            }
//        }
//        return  result;
//    }
    /**
     * 递归循环 计算各目录结构的值
     * @param orgHealthCategoryList
     * @param dimenListResult
     * @param
     * @return
     */
    public List<Map<String,Object>> allCategoryResultMap(List<String> quotaCodes,List<Map<String,Object>> orgHealthCategoryList,List<Map<String, Object>> dimenListResult ){
        List<Map<String,Object>> resultMap = new ArrayList<>();
        for(int i=0 ; i < orgHealthCategoryList.size() ; i++ ){
            Map<String,Object> mapCategory = orgHealthCategoryList.get(i);
            Map<String,Object> map = new HashMap<>();
            double parentResult = 0;
            mapCategory.put(firstColumnField,mapCategory.get("text"));
            map = getParentAllChildren(quotaCodes,mapCategory,map, dimenListResult,parentResult);
            if(map == null || map.size() == 0 ){
                for(String quotaCode : quotaCodes){
                    map.put(quotaCode,0);
                }
                map.put(resultField,0);
            }
            mapCategory.putAll(map);
            resultMap.add(mapCategory);
            if(mapCategory.get("children") != null){
                List<Map<String,Object>> childrenOrgHealthCategoryList = (List<Map<String, Object>>) mapCategory.get("children");
                mapCategory.put("children",allCategoryResultMap(quotaCodes,childrenOrgHealthCategoryList,dimenListResult));
            }
        }
        return  resultMap;
    }
    //获取该节点下所有末节点的结果和
    public   Map<String,Object> getParentAllChildren(List<String> quotaCodes, Map<String,Object> mapCategory,Map<String,Object> returnMap, List<Map<String, Object>> dimenListResult, double parentResult ){
        try {
                boolean childrenFlag = false;
                if(mapCategory.get("children") != null){
                    List<Map<String,Object>> childrenOrgHealthCategoryList = (List<Map<String, Object>>) mapCategory.get("children");
                    if(childrenOrgHealthCategoryList != null && childrenOrgHealthCategoryList.size() > 0){
                        childrenFlag = true;
                    }
                }
                if(childrenFlag){
                    List<Map<String,Object>> childrenOrgHealthCategoryList = (List<Map<String, Object>>) mapCategory.get("children");
                    for(int j=0 ; j < childrenOrgHealthCategoryList.size() ; j++ ){
                        Map<String,Object> childrenMapCategory = childrenOrgHealthCategoryList.get(j);
                        returnMap =  getParentAllChildren(quotaCodes ,childrenMapCategory,returnMap, dimenListResult,parentResult);
                    }
                }else{
                    for(Map<String, Object> dimenMap :dimenListResult){
                        if(dimenMap.get(orgHealthCategoryCode) != null && dimenMap.get(resultField) != null){
                            if(dimenMap.get(orgHealthCategoryCode).equals(mapCategory.get("code"))){
                                double result = Double.parseDouble(dimenMap.get(resultField).toString());
                                double oldResult = 0;
                                if(returnMap.get(resultField) != null){
                                    oldResult = Double.parseDouble(returnMap.get(resultField).toString());
                                }
                                returnMap.put(resultField, basesicUtil.decimalPointHandle(result + oldResult));
                                for(String quotaCode : quotaCodes){
                                    double quotaResult = Double.parseDouble(dimenMap.get(quotaCode).toString());
                                    double oldQuotaResult = 0;
                                    if( returnMap.get(quotaCode) != null ){
                                        oldQuotaResult = Double.parseDouble(returnMap.get(quotaCode).toString());
                                    }
                                    returnMap.put(quotaCode, basesicUtil.decimalPointHandle(quotaResult + oldQuotaResult));
                                }
                                break;
                            }
                        }
                    }
                }
        }catch (Exception e){
            throw new NumberFormatException("统计数据转换异常");
        }
        return returnMap;
    }
    /**
     * 时间聚合查询指标结果
     * @param code
     * @param dimension 多维度 ; 分开
     * @param filter
     * @throws Exception
     */
    public  List<Map<String, Object>> getTimeAggregationResult(String code,String dimension, String filter,String dateDime) throws Exception {
        TjQuota tjQuota= quotaDao.findByCode(code);
        Map<String,String>  dimensionDicMap = getDimensionDicMap(code,dimension);
        List<String> dimenList = getDimenList(dimension);
        String groupDimension = joinDimen(dimension);
        List<Map<String, Object>> dimenListResult = esResultExtract.searcherSumByGroupByTime(tjQuota, groupDimension, filter, dateDime);
        List<Map<String, Object>> resultList = new ArrayList<>();
        String dateHist = "date_histogram(field=quotaDate,interval="+ dateDime +")";
        for(Map<String, Object> map : dimenListResult){
            Map<String,Object> dataMap = new HashMap<>();
            for(String key :map.keySet()){
                if(key.equals(dateHist)) {
                    String value = "";
                    if (dateDime.equals("year")) {
                        value = map.get(key).toString().substring(0, 4);
                    } else if (dateDime.contains("quarter")) {
                        String y = map.get(key).toString().substring(0, 4);
                        String q = map.get(key).toString().substring(5, 7);
                        if(q.contains("01")){
                            value = y + "年1季度";
                        }else if(q.contains("04")){
                            value = y + "年2季度";
                        }else if(q.contains("07")){
                            value = y + "年3季度";
                        }else if(q.contains("10")){
                            value = y + "年4季度";
                        }
                    } else if (dateDime.contains("month")) {
                        value = map.get(key).toString().substring(0, 7);
                    } else if (dateDime.contains("week")) {
                        value = map.get(key).toString().substring(0, 7);
                    } else if (dateDime.contains("day")) {
                        value = map.get(key).toString().substring(0, 10);
                    }
                    dataMap.put(dateDime, value);
                }
                if(dimenList.contains(key)){
                    if(dimensionDicMap.get(map.get(key).toString().toLowerCase())  != null){
                        String dictVal = dimensionDicMap.get(map.get(key).toString().toLowerCase());
                        dataMap.put(key+"Name",dictVal);
                        dataMap.put(key,map.get(key).toString());
                        dataMap.put(firstColumnField, dictVal);
                    }else {
                        if(key.equals(quotaDateField)){
                            String dateFormat = "yyyy-MM-dd";
                            if (dateDime.equals("year")) {
                                dateFormat = "yyyy";
                            }else if(dateDime.equals("month")){
                                dateFormat = "yyyy-MM";
                            }
                            SimpleDateFormat format =  new SimpleDateFormat(dateFormat);
                            Long time = new Long(Long.valueOf(map.get(key).toString()));
                            String quotaDate = format.format(time);
                            dataMap.put(key, quotaDate);
                        }else {
                            dataMap.put(key,map.get(key));
                        }
                    }
                }
                //维度为特殊机构类型时
                if(key.equals(orgHealthCategoryCode)){
                    dataMap.put(map.get(orgHealthCategoryCode).toString(),map.get(orgHealthCategoryCode));
                    dataMap.put(firstColumnField,map.get("text"));
                }
                if(key.equals("SUM(result)")){
                    dataMap.put(resultField, basesicUtil.decimalPointHandle(map.get(key)));
                }
            }
             resultList.add(dataMap);
         }
        return resultList;
    }
    /**
     * 获取聚合查询指标结果
     * @param code
     * @param dimension 多维度 ; 分开
     * @param filter
     * @throws Exception
     */
    public  List<Map<String, Object>> getOrgHealthCategoryAggregationResult(String code,String dimension, String filter, String top) throws Exception {
        TjQuota tjQuota= quotaDao.findByCode(code);
        String groupDimension = "";
        if(dimension.contains(";")){
            String[] dimens =  dimension.split(";");
            for(int i =0 ;i<dimens.length ;i++){
                groupDimension += dimens[i] + ",";
            }
            groupDimension = groupDimension.substring(0,groupDimension.length()-1);
        }else {
            groupDimension = dimension;
        }
        List<Map<String, Object>>  dimenListResult = null;
        if (StringUtils.isNotEmpty(top)) {
            dimenListResult = esResultExtract.searcherSumGroup(tjQuota, groupDimension, filter, resultField, groupDimension, "asc", "1000");
            if (dimenListResult != null && dimenListResult.size() > 0) {
                dimenListResult = dimenListResult.subList(0, dimenListResult.size() > Integer.parseInt(top) ? Integer.parseInt(top) : dimenListResult.size());
            }
        }else {
            dimenListResult = esResultExtract.searcherSumGroup(tjQuota, groupDimension, filter, resultField, groupDimension, "asc", top);
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(Map<String, Object> map : dimenListResult){
            Map<String,Object> dataMap = new HashMap<>();
            boolean quotaFlag = false;
            for(String key :map.keySet()){
                //维度为特殊机构类型时
                if(key.equals(orgHealthCategoryCode)){
                    dataMap.put(map.get(orgHealthCategoryCode).toString(),map.get(orgHealthCategoryCode));
                }
                if(key.equals("SUM(result)")){
                    dataMap.put(resultField, basesicUtil.decimalPointHandle(map.get(key)));
                }
                if(key.equals(quotaDateField)){
                    SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
                    Long time = new Long(Long.valueOf(map.get(key).toString()));
                    String quotaDate = format.format(time);
                    dataMap.put(quotaDateField, quotaDate);
                    quotaFlag = true;
                }
            }
            if(quotaFlag){
                map.remove(quotaDateField);
            }
            dataMap.putAll(map);
            resultList.add(dataMap);
        }
        return resultList;
    }
    /**
     * 获取  特殊机构类别  聚合查询指标结果
     * @param code
     * @param dimension 多维度 ; 分开
     * @param filter
     * @throws Exception
     */
    public  List<Map<String, Object>> getAggregationResult(String code,String dimension, String filter, String top) throws Exception {
        TjQuota tjQuota= quotaDao.findByCode(code);
        Map<String,String>  dimensionDicMap = getDimensionDicMap(code,dimension);
        List<String> dimenList = getDimenList(dimension);
        String groupDimension = joinDimen(dimension);
        List<TjQuotaDimensionSlave> slaves = tjDimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(code);
        for(TjQuotaDimensionSlave slave :slaves) {
            if (slave.getSlaveCode().equals("dept")) {
                String dimenName = dimension + "Name not in('其他') ";
                if(StringUtils.isEmpty(filter)){
                    filter = dimenName;
                }else {
                    filter += " and " + dimenName;
                }
            }
        }
        List<Map<String, Object>>  dimenListResult = null;
        if (StringUtils.isNotEmpty(top)) {
            dimenListResult = esResultExtract.searcherSumGroup(tjQuota, groupDimension, filter, resultField, groupDimension, "asc", "1000");
            if (dimenListResult != null && dimenListResult.size() > 0) {
                dimenListResult = dimenListResult.subList(0, dimenListResult.size() > Integer.parseInt(top) ? Integer.parseInt(top) : dimenListResult.size());
            }
        }else {
            dimenListResult = esResultExtract.searcherSumGroup(tjQuota, groupDimension, filter, resultField, groupDimension, "asc", top);
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(Map<String, Object> map : dimenListResult){
            Map<String,Object> dataMap = new HashMap<>();
            for(String key :map.keySet()){
                if(dimenList.contains(key)){
                    if(dimensionDicMap.get(map.get(key).toString().toLowerCase())  != null){
                        dataMap.put(key,dimensionDicMap.get(map.get(key).toString().toLowerCase()));
                        dataMap.put(key+"Name",dimensionDicMap.get(map.get(key).toString().toLowerCase()));
                        dataMap.put(key+"Code",map.get(key).toString());
                        dataMap.put(firstColumnField,dimensionDicMap.get(map.get(key).toString().toLowerCase()));
                    }else {
                        dataMap.put(key,map.get(key));
                    }
                }
                //维度为特殊机构类型时
                if(key.equals(orgHealthCategoryCode)){
                    dataMap.put(map.get(orgHealthCategoryCode).toString(),map.get(orgHealthCategoryCode));
                    dataMap.put(firstColumnField,map.get("text"));
                }
                if(key.equals("SUM(result)")){
                    dataMap.put(resultField, basesicUtil.decimalPointHandle(map.get(key)));
                }
            }
            resultList.add(dataMap);
        }
        if (StringUtils.isEmpty(top) && "town".equals(dimension)) {
            resultList = noDataDimenDictionary(resultList,dimension,filter);
        }
        for(TjQuotaDimensionSlave slave :slaves){
            if(slave.getSlaveCode().equals("sex") ){
                resultList = filteUnKnowSex(resultList, dimension);
            }
        }
        if(dimension.equals("level")){
            resultList = filteUnKnowLeve(resultList, dimension);
        }
        return resultList;
    }
    /**
     * 过滤未说明的性别,和其他为0的数据
     * @param dataList
     * @return
     */
    public List<Map<String, Object>> filteUnKnowSex(List<Map<String, Object>> dataList,String dimension){
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(Map<String,Object> map : dataList){
            if(map.get(dimension) !=null){
                if( !map.get(dimension).toString().contains("未说明")){
                    if(map.get(resultField) !=null){
                        if(!map.get(dimension).toString().contains("未知") || ! map.get(resultField).toString().equals("0") ){
                            resultList.add(map);
                        }
                    }
                }
            }
        }
        return  resultList;
    }
    /**
     * 过滤未知的等级
     * @param dataList
     * @return
     */
    public List<Map<String, Object>> filteUnKnowLeve(List<Map<String, Object>> dataList,String dimension){
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(Map<String,Object> map : dataList){
            if(map.get(dimension) !=null){
                if( !(map.get(dimension).toString().contains("未知") || map.get(dimension).toString().contains("9")) ){
                    resultList.add(map);
                }
            }
        }
        return  resultList;
    }
    /**
     * 查询结果 对无数据的字典项补0
     * @param  dataList 数据集合
     * @param dimen 维度
     * @return
     */
    public List<Map<String, Object>> noDataDimenDictionary(List<Map<String, Object>> dataList,String dimen,String filter){
        Map<String, Object> dictMap = new HashMap<>();
        if(dimen.equals("town")){
            String sql = "";
            if(dimen.equals("town") ){
                sql = "SELECT id as code,name as name  from address_dict where pid = '361100'";
                List<Map<String, Object>> dictDataList = jdbcTemplate.queryForList(sql);
                if(null != dictDataList) {
                    for(int i = 0 ; i < dictDataList.size();i++){
                        if(null != dictDataList.get(i).get("code") && null != dictDataList.get(i).get("name")){
                            dictMap.put(dictDataList.get(i).get("code").toString(),dictDataList.get(i).get("name").toString());
                        }
                    }
                }
            }
            List<Map<String, Object>> resultList = new ArrayList<>();
            for(String code : dictMap.keySet()){
                Map<String,Object> oneMap = new HashMap<>();
                String result = "0";
                for(Map<String,Object> map : dataList){
                    if(map.get(dimen) !=null && map.get(dimen).equals(dictMap.get(code))){
                        result = map.get(resultField).toString();
                        break;
                    }
                }
                oneMap.put(firstColumnField,dictMap.get(code));
                oneMap.put(dimen,dictMap.get(code));
                oneMap.put(dimen+"Name",dictMap.get(code));
                oneMap.put(dimen+"Code",code);
                oneMap.put(resultField,result);
                resultList.add(oneMap);
            }
            return  resultList;
        }
        return  dataList;
    }
    /**
     * 拼接维度分组
     * @param dimension
     * @return
     */
    public String joinDimen(String dimension){
        String groupDimension = "";
        if(dimension.contains(";")){
            String[] dimens =  dimension.split(";");
            for(int i =0 ;i<dimens.length ;i++){
                groupDimension += dimens[i] + ",";
            }
            groupDimension = groupDimension.substring(0,groupDimension.length()-1);
        }else {
            groupDimension = dimension;
        }
        return groupDimension;
    }
    /**
     * 获取维度List
     * @param dimension
     * @return 多维度 ;隔开
     */
    public List<String> getDimenList(String dimension){
        List<String> dimenList = new ArrayList<>();
        if(dimension.contains(";")){
            String[] dimens =  dimension.split(";");
            for(int i =0 ;i<dimens.length ;i++){
                dimenList.add(dimens[i]);
            }
        }else {
            dimenList.add(dimension);
        }
        return dimenList;
    }
    /**
     * 获取指标维度字典项
     * @param quotaCode
     * @param dimension 多维度 ;隔开
     * @return
     */
    public Map<String,String>  getDimensionDicMap(String quotaCode ,String dimension){
        Map<String,String>  dimensionDicMap = new HashMap<>();
        String[] dimens =  dimension.split(";");
        for(int i =0 ;i<dimens.length ;i++){
            String dictSql = getQuotaDimensionDictSql(quotaCode, dimens[i]);
            if(StringUtils.isNotEmpty(dictSql)){
                Map<String,String> dicMap = getDimensionMap(dictSql, dimens[i]);
                for(String key :dicMap.keySet()){
                    dimensionDicMap.put(key.toLowerCase(),dicMap.get(key));
                }
            }
        }
        return dimensionDicMap;
    }
    /**
     * 获取维度的字典 sql  -- 针对于查询结果 从ES库查询结果
     * @param quotaCode
     * @param dimension
     * @return
     */
    private String getQuotaDimensionDictSql(String quotaCode, String dimension) {
        boolean mainFlag = dimension.contains("province") || dimension.contains("city") ||dimension.contains("town")
                ||dimension.contains("org") ||dimension.contains("dept") ||dimension.contains("year") ||dimension.contains("quarter")
                ||dimension.contains("month") ||dimension.contains("day") || dimension.contains(quotaDateField) ;
        String dictSql = "";
        //查询维度 sql
        if( mainFlag){
            List<TjQuotaDimensionMain>  dimensionMains = tjDimensionMainService.findTjQuotaDimensionMainByQuotaCode(quotaCode);
            if(dimensionMains != null && dimensionMains.size() > 0){
                for(TjQuotaDimensionMain main:dimensionMains){
                    if(main.getMainCode().equals(dimension)){
                        dictSql = main.getDictSql();
                    }
                }
            }
        }else {
            if(StringUtils.isEmpty(dictSql)) {
                List<TjQuotaDimensionSlave> dimensionSlaves = tjDimensionSlaveService.findTjQuotaDimensionSlaveByQuotaCode(quotaCode);
                if (dimensionSlaves != null && dimensionSlaves.size() > 0) {
                    if(StringUtils.isNotEmpty(dimension)){
                        String n = dimension.substring(dimension.length() - 1, dimension.length());
                        if(StringUtils.isNotEmpty(n) && (n.equals("1") || n.equals("2") || n.equals("3") || n.equals("4")) ){
                            int slave = Integer.valueOf(n);
                            if(dimensionSlaves.size() >= slave){
                                dictSql = dimensionSlaves.get(slave-1).getDictSql();
                            }
                        }
                    }
                }
            }
        }
        return dictSql;
    }
    /**
     *获取字典项数据集
     * @param dictSql
     * @param dimension
     * @return
     */
    public Map<String,String> getDimensionMap(String dictSql, String dimension) {
        Map<String,String> dimensionDicMap = new HashMap<>();
        if(StringUtils.isNotEmpty(dictSql)) {
            BasesicUtil baseUtil = new BasesicUtil();
            boolean main = dimension.contains("province") || dimension.contains("city") ||dimension.contains("town")
                    ||dimension.contains("org") ||dimension.contains("dept") ||dimension.contains("year") ||dimension.contains("month")
                    ||dimension.contains("quarter") ||dimension.contains("day");
            if( main){
                //主纬度字典项
                List<SaveModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(SaveModel.class));
                if(dictDatas != null ) {
                    for (SaveModel saveModel : dictDatas) {
                        String name = baseUtil.getFieldValueByName(dimension + "Name", saveModel);
                        String val = baseUtil.getFieldValueByName(dimension, saveModel);
                        if(StringUtils.isNotEmpty(val) && StringUtils.isNotEmpty(name)){
                            dimensionDicMap.put(val.toLowerCase(),name);
                        }
                    }
                }
            } else{
                //查询细维度字典数据
                List<DictModel> dictDatas = jdbcTemplate.query(dictSql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel dictModel : dictDatas) {
                    String name = baseUtil.getFieldValueByName("name", dictModel);
                    String val = baseUtil.getFieldValueByName("code", dictModel).toLowerCase();
                    dimensionDicMap.put(val,name);
                }
            }
        }
        return dimensionDicMap;
    }
    /**
     * 获取单个指标结果
     * @param code
     * @param filters 外部传入条件
     * @param dimension
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>>  getSimpleQuotaReport(String code,String filters,String dimension,boolean isTrunTree, String top) throws Exception {
        String dateType = "";
        //指标的展示维度,由视图中决定
        if(dimension.trim().equals("year")){
            dateType = "year";
            dimension = "";
        }else if(dimension.trim().equals("quarter")){
            dateType = "quarter";
            dimension = "";
        }else if(dimension.trim().equals("month")){
            dateType = "month";
            dimension = "";
        }else if(dimension.trim().equals("day")){
            dateType = "day";
            dimension = "";
        }
        List<Map<String, Object>> result = new ArrayList<>();
        TjQuotaDataSource quotaDataSource = dataSourceService.findSourceByQuotaCode(code);
        JSONObject obj = new JSONObject().fromObject(quotaDataSource.getConfigJson());
        EsConfig esConfig= (EsConfig) JSONObject.toBean(obj,EsConfig.class);
        String configFilter = esConfig.getFilter();
        if(StringUtils.isNotEmpty(configFilter) && quotaDataSource.getSourceCode().equals("1")){//数据源为ES库
            TjQuotaDataSave quotaDataSave = dataSaveService.findByQuota(code);
            if(quotaDataSave != null && StringUtils.isNotEmpty(quotaDataSave.getConfigJson())){
                JSONObject objSave = new JSONObject().fromObject(quotaDataSave.getConfigJson());
                EsConfig esConfigSave = (EsConfig) JSONObject.toBean(objSave,EsConfig.class);
                if(StringUtils.isEmpty(esConfig.getIndex()) || esConfig.getIndex().equals(esConfigSave.getIndex()) ){
                    if(StringUtils.isNotEmpty(filters)){
                        filters += " and " + configFilter;
                    }else {
                        filters = configFilter;
                    }
                }
            }else {
                if(StringUtils.isNotEmpty(filters)){
                    filters += " and " + configFilter;
                }else {
                    filters = configFilter;
                }
            }
        }
        // 判断该指标是否需要同比, 需要的话拼接时间条件
        if (StringUtils.isNotEmpty(esConfig.getIncrementFlag())) {
            filters = filtersExchangeHandle(filters, esConfig);
            log.info("filters = {}", filters);
        }
        String molecularFilter = filters;
        String denominatorFilter = filters;
        if (StringUtils.isNotEmpty(esConfig.getGrowthFlag())) {
            //增幅运算(环比和同比)
            result = getGrowthByQuota(dimension, filters, esConfig, dateType, top);
        } else {
            if (StringUtils.isNotEmpty(esConfig.getDateComparisonType())) {
                //时间条件处理
                filters = getdateComparisonTypeFilter(esConfig,filters);
            }
            if( (StringUtils.isNotEmpty(esConfig.getEspecialType())) && esConfig.getEspecialType().equals(orgHealthCategory)){
//                //特殊机构类型查询输出结果  只有查询条件没有维度 默认是 机构类型维度
//                result = getOrgHealthCategory(code,filters,dateType,isTrunTree, top);
            }else if( (StringUtils.isNotEmpty(esConfig.getMolecular())) && StringUtils.isNotEmpty(esConfig.getDenominator())){//除法
                //除法指标查询输出结果
                molecularFilter = handleFilter(esConfig.getMolecularFilter(), molecularFilter);
                denominatorFilter = handleFilter(esConfig.getDenominatorFilter(), denominatorFilter);
                if (StringUtils.isNotEmpty(esConfig.getDivisionType()) && esConfig.getDivisionType().equals("2")) {
                    result = divisionQuotaDenoConstant(esConfig.getMolecular(), dimension, molecularFilter, denominatorFilter,esConfig.getPercentOperation(), esConfig.getPercentOperationValue(), dateType, top);
                } else {
                    result = divisionQuota(esConfig.getMolecular(), esConfig.getDenominator(), dimension, molecularFilter, denominatorFilter, esConfig.getPercentOperation(), esConfig.getPercentOperationValue(),dateType, top);
                }
                //计算除法 合计
                String moleQuotaCode = getBasicQuota(esConfig.getMolecular());
                moleQuotaCode = " quotaCode='" + moleQuotaCode.replaceAll("_", "") + "' ";
                String denoQuotaCode = getBasicQuota(esConfig.getDenominator());
                denoQuotaCode = " quotaCode='" + denoQuotaCode.replaceAll("_", "") + "' ";
                if(StringUtils.isEmpty(molecularFilter)){
                    molecularFilter =  moleQuotaCode;
                }else {
                    molecularFilter += " and " + moleQuotaCode;
                }
                if(StringUtils.isEmpty(denominatorFilter)){
                    denominatorFilter =  denoQuotaCode;
                }else {
                    denominatorFilter += " and " + denoQuotaCode;
                }
                String moleTotalSql = "select sum(result) result from  medical_service_index where " + molecularFilter;
                String denoTotalSql = "select sum(result) result from  medical_service_index where " + denominatorFilter;
                double moleTotal = 0;
                double denoTotal = 0;
                List<Map<String, Object>> moleListMap = elasticsearchUtil.excuteDataModel(moleTotalSql.toString());
                if(moleListMap != null &&  moleListMap.size() > 0){
                    if(moleListMap.get(0).get("result") != null){
                        moleTotal = Double.valueOf(moleListMap.get(0).get("result").toString());
                    }
                }
                List<Map<String, Object>> denoListMap = elasticsearchUtil.excuteDataModel(denoTotalSql.toString());
                if(denoListMap != null &&  denoListMap.size() > 0){
                    if(denoListMap.get(0).get("result") != null){
                        denoTotal = Double.valueOf(denoListMap.get(0).get("result").toString());
                    }
                }
                double point = 0;
                int operation = Integer.valueOf(esConfig.getPercentOperation());
                int operationValue = Integer.valueOf(esConfig.getPercentOperationValue());
                if(denoTotal - 0 != 0){
                    if(moleTotal != 0){
                        if(operation == 1){
                            point = (moleTotal/denoTotal) * operationValue;
                        }else if(operation == 2){
                            point = (moleTotal/denoTotal) / operationValue;
                        }
                    }
                }
                Map<String, Object> totalMap = new HashMap<>();
                totalMap.put(resultField, basesicUtil.decimalPointHandle(point));
                totalMap.put(dimension,"合计");
                totalMap.put(firstColumnField,"合计");
                result.add(totalMap);
            }else if(StringUtils.isNotEmpty(esConfig.getAddOperation())){
                String firstFilter = handleFilter(esConfig.getAddFirstFilter(), filters);
                String secondFilter = handleFilter(esConfig.getAddSecondFilter(), filters);
                result = addQuota(esConfig.getAddFirstQuotaCode(), firstFilter, esConfig.getAddSecondQuotaCode(), secondFilter, esConfig.getAddOperation(),dimension,dateType, top);
            }else if(StringUtils.isNotEmpty(esConfig.getSuperiorBaseQuotaCode())) {
                //二次统计 指标查询
                result = getQuotaResultList(esConfig.getSuperiorBaseQuotaCode(), dimension,filters,dateType, top);
            }else {
                //普通基础指标查询
                result = getQuotaResultList(code, dimension,filters,dateType, top);
            }
        }
        return result;
    }
    //时间对比类型 时的 查询条件处理
    public String getdateComparisonTypeFilter(EsConfig esConfig,String filters){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Map<String,String> filterMap = new HashMap<>();
        if(StringUtils.isNotEmpty(filters)){
            String [] filter = filters.split("and");
            String year = "";
            String month = "";
            String day = "";
            if(filter.length > 0 ){
                for(String key : filter){
                    filterMap.put(key,key);
                    Date date = new Date();
                    if(key.contains(quotaDateField)){
                        //quotaDate >= '2018-03-01'
                        String dateStr = key.substring(key.indexOf("'")+1,key.lastIndexOf("'"));
                        date = DateUtil.parseDate(dateStr,DateUtil.DEFAULT_DATE_YMD_FORMAT);
                    }
                    if(esConfig.getDateComparisonType().equals("lastYear")){
                        c.setTime(date);
                        c.add(Calendar.YEAR, -1);
                        Date lastYear = c.getTime();
                        filterMap.put(key,format.format(lastYear));
                    }else if(esConfig.getDateComparisonType().equals("lastMonth")) {
                        c.setTime(date);
                        c.add(Calendar.MONTH, -1);
                        Date lastYear = c.getTime();
                        filterMap.put(key,format.format(lastYear));
                    }else if(esConfig.getDateComparisonType().equals("lastDay")) {
                        c.setTime(date);
                        c.add(Calendar.DATE, -1);
                        Date lastYear = c.getTime();
                        filterMap.put(key,format.format(lastYear));
                    }
                }
            }
            filters = "";
            if(filterMap != null && filterMap.size() > 0){
                for(String key : filterMap.keySet()){
                    if(StringUtils.isEmpty(filters)){
                        filters = filterMap.get(key);
                    }else {
                        filters = " and " + filterMap.get(key);
                    }
                }
            }
        }
        return  filters;
    }
    public String handleFilter(String secondFilter, String resultFilter) {
        if (StringUtils.isNotEmpty(secondFilter)) {
            if (StringUtils.isEmpty(resultFilter)) {
                resultFilter = secondFilter;
            } else {
                resultFilter += " and " + secondFilter;
            }
        }
        return resultFilter;
    }
    /**
     * 门急诊费用
     * @return
     */
    public String getCostOfOutPatient() {
        String sum = "0";
        String sql = "select sum(result) from medical_service_index where quotaCode='HC041047'";
        List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sql);
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            for (Map<String, Object> map : listData) {
                sum = basesicUtil.decimalPointHandle(map.get("SUM(result)"));
            }
        }
        return sum;
    }
    /**
     * 门急诊人次
     * @return
     */
    public String getNumOfOutPatient() {
        int sum = 0;
        String sql = "select sum(result) from medical_service_index where quotaCode='HC041008'";
        List<Map<String, Object>> listData = singleDiseaseService.parseIntegerValue(sql);
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            for (Map<String, Object> map : listData) {
                String value = basesicUtil.decimalPointHandle(map.get("SUM(result)"));
                sum += Integer.parseInt(value);
            }
        }
        return sum + "";
    }
    /**
     * 入院费用
     * @return
     */
    public String getCostOfInPatient() {
        String sum = "0";
        String sql = "select sum(result) from medical_service_index where quotaCode='HC041068'";
        List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sql);
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            for (Map<String, Object> map : listData) {
                sum = basesicUtil.decimalPointHandle(map.get("SUM(result)"));
            }
        }
        return sum;
    }
    /**
     * 入院人次
     * @return
     */
    public String getNumOfInPatient() {
        int sum = 0;
        String sql = "select sum(result) from medical_service_index where quotaCode='HC041000'";
        List<Map<String, Object>> listData = singleDiseaseService.parseIntegerValue(sql);
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            for (Map<String, Object> map : listData) {
                String value = basesicUtil.decimalPointHandle(map.get("SUM(result)"));
                sum += Integer.parseInt(value);
            }
        }
        return sum + "";
    }
    public String getCostOfMedicalMonitor() {
        // 获取门急诊费用
        Double costOfOutPatient = Double.parseDouble(getCostOfOutPatient());
        // 获取入院费用
        Double costOfInPatient = Double.parseDouble(getCostOfInPatient());
        // 医疗费用监测 = 获取门急诊费用 + 获取入院费用
        Double costOfMedicalMonitor = costOfInPatient + costOfOutPatient;
        return basesicUtil.decimalPointHandle(costOfMedicalMonitor);
    }
    /**
     * 数据查询
     * @return
     */
    public Map<String, List<String>> getDataInfo(String sql ,String xdataName) {
        List<Map<String, Object>> listData = parseIntegerValue(sql);
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> valueData = new ArrayList<>();
        if (null != listData  && listData.size() >0 && listData.get(0) !=null ) {
            listData.forEach(one -> {
                if(xdataName.contains("date_histogram")){
                    if(xdataName.contains("year")){
                        xData.add(one.get(xdataName).toString().substring(0,4) + "");
                    }else if(xdataName.contains("quarter")){
                        String quarter = "";
                        if(one.get(xdataName) != null){
                           String value = one.get(xdataName).toString();
                            String y = value.substring(0, 4);
                            String q = value.substring(5, 7);
                            if(q.contains("01")){
                                quarter = y + "年1季度";
                            }else if(q.contains("04")) {
                                value = y + "年2季度";
                            }else if(q.contains("07")){
                                quarter = y + "年3季度";
                            }else if(q.contains("10")){
                                quarter = y + "年4季度";
                            }
                            xData.add(quarter);
                        }
                    }else if(xdataName.contains("month")){
                        xData.add(one.get(xdataName).toString().substring(0,7) + "");
                    }
                }else {
                    xData.add(one.get(xdataName) + "");
                }
                valueData.add(one.get("count") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     * 对查询结果key包含count、sum的value去掉小数点
     * @param sql
     * @return
     */
    public List<Map<String, Object>> parseIntegerValue(String sql) {
        List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sql);
            List<Map<String, Object>> handleData = new ArrayList<>();
        listData.forEach(item -> {
            Map<String, Object> myMap = new HashMap<>();
            item.forEach((k,v) -> {
                if (k.contains("COUNT") || k.contains("SUM") || k.contains("count")) {
                    v = (int) Double.parseDouble(v + "");
                }
                myMap.put(k,v);
            });
            handleData.add(myMap);
        });
        return handleData;
    }
    /**
     * 百分比 增幅运算 维度不是时间维度
     * @param dimension
     * @param moleList
     * @param denoList
     * @param operation
     * @param operationValue
     * @return
     */
    public List<Map<String, Object>> divisionPercent(String dimension, List<Map<String, Object>> moleList, List<Map<String, Object>> denoList,int operation,int operationValue){
        List<Map<String, Object>> divisionResultList = new ArrayList<>();
        for(Map<String, Object> denoMap : denoList) {
            if (null != denoMap && denoMap.size() > 0 ) {
                Map<String, Object> map = new HashMap<>();
                double denoResultVal = Double.valueOf(denoMap.get(resultField) == null ? "0" : denoMap.get(resultField).toString());
                String denoKeyVal = "";
                String [] denoDimensions = dimension.split(";");
                for(int i = 0 ;i < denoDimensions.length ; i++){
                    if(i == 0){
                        denoKeyVal = denoMap.get(denoDimensions[i]).toString();
                    }else {
                        denoKeyVal = denoKeyVal + "-" + denoMap.get(denoDimensions[i]).toString() ;
                    }
                    map.put(firstColumnField, denoMap.get(firstColumnField));
                    map.put(denoDimensions[i], denoMap.get(denoDimensions[i]).toString());
                }
                if (denoResultVal == 0) {
                    map.put(resultField, "--");
                    divisionResultList.add(map);
                } else {
                    if(moleList != null && moleList.size() > 0){
                        for(Map<String, Object> moleMap :moleList) {
                            String moleKeyVal = "";
                            String [] moleDimensions = dimension.split(";");
                            for(int i = 0 ;i < moleDimensions.length ; i++){
                                if(i == 0){
                                    moleKeyVal = moleMap.get(moleDimensions[i]).toString();
                                }else {
                                    moleKeyVal = moleKeyVal + "-" + moleMap.get(moleDimensions[i]).toString() ;
                                }
                            }
                            if(denoKeyVal.equals(moleKeyVal)){
                                double point = 0;
                                float moleResultVal = Float.valueOf(moleMap.get(resultField).toString());
                                point = ((moleResultVal - denoResultVal)/denoResultVal) * operationValue;
                                map.put(resultField, basesicUtil.decimalPointHandle(point));
                                divisionResultList.add(map);
                                break;
                            }
                        }
                    }else {
                        map.put(resultField, 0);
                        divisionResultList.add(map);
                    }
                }
            }
        }
        Double moleVal = caculateResult(moleList);
        Double denoVal = caculateResult(denoList);
        if (0 != denoVal) {
            Map<String, Object> map = new HashMap<>();
            double result = (moleVal - denoVal) / denoVal * operationValue;
            map.put("result", basesicUtil.decimalPointHandle(result));
            map.put("firstColumn", "合计");
            map.put(dimension, "合计");
            divisionResultList.add(map);
        }
        return  divisionResultList;
    }
    /**
     * 计算增幅 环比和 同比
     * @param dimension 不为空时,查询固定某个月或者某年的增幅
     * @param filters  外部过滤条件 如 quotaDate >= '2018-03-01' and quotaDate <= '2018-03-31'
     * @param esConfig 指标内部配置
     * @param dateType 不为空时,查询某个时间区间的增幅
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getGrowthByQuota(String dimension, String filters, EsConfig esConfig, String dateType, String top) throws Exception {
        List<Map<String, Object>>  resultList = new LinkedList<>();
        String startQuotaDate = "";
        String endQuotaDate = "";
        String noDateFilter = "";
        if(StringUtils.isNotEmpty(esConfig.getDenominatorFilter()) ){
            noDateFilter = esConfig.getDenominatorFilter();
        }
        if (StringUtils.isNotEmpty(filters) && filters.contains(quotaDateField)) {// 外部指定时间
            String params [] = filters.split("and ");
            for(int i =0 ;i< params.length ;i++){
                String quotaDateParam = params[i];
                if(quotaDateParam.contains(quotaDateField)){
                    boolean b = quotaDateParam.indexOf("'") > -1;
                    int start = b ? quotaDateParam.indexOf("'") : quotaDateParam.indexOf("\"");//查询条件不是' ,就是"
                    if(quotaDateParam.contains(">")){
                        startQuotaDate = quotaDateParam.substring(start + 1, start + 11);
                    }
                    if(quotaDateParam.contains("<")){
                        endQuotaDate = quotaDateParam.substring(start + 1, start + 11);
                    }
                }else{
                    if(StringUtils.isNotEmpty(noDateFilter)){
                        noDateFilter += " and " + quotaDateParam;
                    }else {
                        noDateFilter = quotaDateParam;
                    }
                }
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar lastDate = Calendar.getInstance();
        String molecularFilter = "";
        String denominatorFilter = "";
        String growthFlag = esConfig.getGrowthFlag();
        if(StringUtils.isEmpty(dateType)){
            if ("1".equals(growthFlag)) { // 年增幅  没有传时间条件默认当前年份
                int now;
                int beforeNow;
                now = lastDate.get(Calendar.YEAR);
                if (StringUtils.isNotEmpty(endQuotaDate)) {// 外部指定时间
                    now = Integer.parseInt(endQuotaDate.substring(0,4));
                }
                beforeNow = now - 1;
                molecularFilter = "quotaDate >= '" + now + "-01-01' and quotaDate <= '" + now + "-12-31'";
                denominatorFilter = "quotaDate >= '" + beforeNow + "-01-01' and quotaDate <= '" + beforeNow + "-12-31'";
            } else if ("2".equals(growthFlag)) { // 月增幅  没有传时间条件默认当前月份
                // 如果有时间过滤条件,则按时间条件计算
                if (StringUtils.isNotEmpty(endQuotaDate)) {
                    lastDate.setTime(sdf.parse(endQuotaDate));
                }
                lastDate.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
                String firstDay = sdf.format(lastDate.getTime());
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                String lastDay = sdf.format(lastDate.getTime());
                lastDate.add(Calendar.MONTH, -1);
                lastDate.set(Calendar.DAY_OF_MONTH, 1);
                String preMonthFirstDay = sdf.format(lastDate.getTime());
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                String preMonthLastDay = sdf.format(lastDate.getTime());
                log.info("firstDay = {}, lastDay = {}", firstDay, lastDay);
                log.info("preMonthFirstDay = {}, preMonthLastDay = {}", preMonthFirstDay, preMonthLastDay);
                molecularFilter = "quotaDate >= '" + firstDay + "' and quotaDate <= '" + lastDay + "'";
                denominatorFilter = "quotaDate >= '" + preMonthFirstDay + "' and quotaDate <= '" + preMonthLastDay + "'";
            } else if ("3".equals(growthFlag)) { // 季度增幅  没有传时间条件默认当前季度
                // 如果有时间过滤条件,则按时间条件计算
                if (StringUtils.isNotEmpty(endQuotaDate)) {
                    lastDate.setTime(sdf.parse(endQuotaDate));
                }
                String firstDay = "";
                String lastDay = "";
                int currentMonth = lastDate.get(Calendar.MONTH) + 1;
                if (currentMonth >= 1 && currentMonth <= 3){
                    lastDate.set(Calendar.MONTH, 0);
                }else if (currentMonth >= 4 && currentMonth <= 6){
                    lastDate.set(Calendar.MONTH, 3);
                } else if (currentMonth >= 7 && currentMonth <= 9){
                    lastDate.set(Calendar.MONTH, 6);
                } else if (currentMonth >= 10 && currentMonth <= 12){
                    lastDate.set(Calendar.MONTH, 9);
                }
                lastDate.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
                firstDay = sdf.format(lastDate.getTime());//这个季度第一天
                lastDate.add(Calendar.MONTH, 3);
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                lastDay = sdf.format(lastDate.getTime());//这个季度最后一天
                lastDate.add(Calendar.MONTH, -6);//前一个季度第一天
                lastDate.set(Calendar.DAY_OF_MONTH, 1);
                lastDate.add(Calendar.MONTH, 3);
                String preMonthFirstDay = sdf.format(lastDate.getTime());
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                String preMonthLastDay = sdf.format(lastDate.getTime());
                log.info("firstDay = {}, lastDay = {}", firstDay, lastDay);
                log.info("preMonthFirstDay = {}, preMonthLastDay = {}", preMonthFirstDay, preMonthLastDay);
                molecularFilter = "quotaDate >= '" + firstDay + "' and quotaDate <= '" + lastDay + "'";
                denominatorFilter = "quotaDate >= '" + preMonthFirstDay + "' and quotaDate <= '" + preMonthLastDay + "'";
            }
            if (StringUtils.isNotEmpty(esConfig.getMolecularFilter())) {
                molecularFilter += " and " + esConfig.getMolecularFilter();
            }
            if (StringUtils.isNotEmpty(esConfig.getDenominatorFilter())) {
                denominatorFilter += " and " + esConfig.getDenominatorFilter();
            }
            if(StringUtils.isNotEmpty(noDateFilter)){
                molecularFilter += " and " + noDateFilter;
                denominatorFilter += " and " + noDateFilter;
            }
            List<Map<String, Object>> moleList = getSimpleQuotaReport(esConfig.getMolecular(), molecularFilter,dimension ,false , top);
            List<Map<String, Object>> denoList =  getSimpleQuotaReport(esConfig.getDenominator(),denominatorFilter,dimension,false, null);
            resultList = divisionPercent(dimension, moleList, denoList, 1, 100);
            return resultList;
        }else {
            String dateFilter = "";
            //按时间维度 增幅,即时间区间增幅
            int nowYear;
            int beforeYear;
            Date firstMonth = new Date();
            Date endMonth = new Date();
            nowYear = lastDate.get(Calendar.YEAR);
            beforeYear = nowYear - 4;
            if ("1".equals(growthFlag)) { // 年增幅  没有传时间条件默认当前年份 向前推3年
                if (StringUtils.isNotEmpty(startQuotaDate)) {// 外部指定时间
                    beforeYear = Integer.parseInt(startQuotaDate.substring(0,4))-1;
                }
                if (StringUtils.isNotEmpty(endQuotaDate)) {// 外部指定时间
                    nowYear = Integer.parseInt(endQuotaDate.substring(0,4));
                    dateFilter = "quotaDate >= '" + beforeYear + "-01-01' and quotaDate <= '" + nowYear + "-12-31'";
                }
            } else if ("2".equals(growthFlag)) { // 月增幅  没有传时间条件默认当前月份 计算前6个月数据 计算向前推7个月
                lastDate.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
                endMonth =lastDate.getTime();
                lastDate.add(Calendar.MONTH, - 7);
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                firstMonth = lastDate.getTime();
                // 如果有时间过滤条件,则按时间条件计算
                if (StringUtils.isNotEmpty(startQuotaDate)) {
                    if (StringUtils.isNotEmpty(startQuotaDate)) {// 外部指定时间
                        firstMonth = sdf.parse(startQuotaDate);
                        lastDate.setTime(firstMonth);
                        lastDate.add(Calendar.MONTH, -1);//向前推一个月 用于计算最后一个月增幅
                        firstMonth = lastDate.getTime();
                    }
                    if (StringUtils.isNotEmpty(endQuotaDate)) {// 外部指定时间
                        endMonth = sdf.parse(endQuotaDate);
                    }
                }
                dateFilter = "quotaDate >= '" + sdf.format(firstMonth) + "' and quotaDate <= '" + sdf.format(endMonth) + "'";
            }else if ("3".equals(growthFlag)) { // 季度增幅  没有传时间条件默认当前季度,计算查询向前推一个季度
                int currentMonth = lastDate.get(Calendar.MONTH) + 1;
                if (currentMonth >= 1 && currentMonth <= 3){
                    lastDate.set(Calendar.MONTH, 0);
                }else if (currentMonth >= 4 && currentMonth <= 6){
                    lastDate.set(Calendar.MONTH, 3);
                } else if (currentMonth >= 7 && currentMonth <= 9){
                    lastDate.set(Calendar.MONTH, 6);
                } else if (currentMonth >= 10 && currentMonth <= 12){
                    lastDate.set(Calendar.MONTH, 9);
                }
                lastDate.set(Calendar.MONTH, 3);//此季度最后一天
                lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                endMonth =lastDate.getTime();
                lastDate.set(Calendar.MONTH, -6);//向前推一个季度 向前推3个月
                lastDate.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
                firstMonth = lastDate.getTime();
                // 如果有时间过滤条件,则按时间条件计算
                if (StringUtils.isNotEmpty(startQuotaDate)) {
                    if (StringUtils.isNotEmpty(startQuotaDate)) {// 外部指定时间
                        firstMonth = sdf.parse(startQuotaDate);
                        lastDate.setTime(firstMonth);
                        lastDate.add(Calendar.MONTH, -3);//向前推一季度 用于计算最后一个季度增幅
                        firstMonth = lastDate.getTime();
                    }
                    if (StringUtils.isNotEmpty(endQuotaDate)) {// 外部指定时间
                        endMonth = sdf.parse(endQuotaDate);
                    }
                }
                dateFilter = "quotaDate >= '" + sdf.format(firstMonth) + "' and quotaDate <= '" + sdf.format(endMonth) + "'";
            }
            if(StringUtils.isNotEmpty(noDateFilter)){
                filters = dateFilter + " and " + noDateFilter;
            }else{
                filters = dateFilter;
            }
            dimension = dateType;
            List<Map<String, Object>> dataList = getSimpleQuotaReport(esConfig.getMolecular(), filters,dimension ,false , null);
            if(dataList != null && dataList.size() > 0){
                if(dateType.toLowerCase().equals("year")){
                    for(int i = nowYear ; i > beforeYear ;i--){
                        double current = 0;
                        double last = 0;
                        Map<String,Object> map = new HashMap<>();
                        map.put(dimension, i);
                        for(Map<String,Object> dataMap : dataList){
                            int y = Integer.valueOf(dataMap.get(dimension).toString());
                            if( y == i ){
                                map.put(firstColumnField, dataMap.get(firstColumnField));
                                current = Double.valueOf(dataMap.get(resultField).toString());
                            }
                            if( y == i-1 ){
                                last = Double.valueOf(dataMap.get(resultField).toString());
                            }
                        }
                        if(last == 0){
                            map.put(resultField,"--");
                        }else {
                            double precent = (current - last)/last*100;
                            map.put(resultField,precent-0 ==0 ? 0 : basesicUtil.decimalPointHandle(precent));
                        }
                        resultList.add(map);
                        if(i-beforeYear <= 0){
                            break;
                        }
                    }
                }else if(dateType.toLowerCase().equals("quarter")){
                    String startQuarter = "";
                    String endQuarter = "";
                    lastDate.setTime(firstMonth);
                    Date firstDate = lastDate.getTime();
                    int currentMonth = lastDate.get(Calendar.MONTH) + 1;
                    if (currentMonth >= 1 && currentMonth <= 3){
                        startQuarter = sdf.format(firstDate).substring(0,4)+"年1季度";
                    }else if (currentMonth >= 4 && currentMonth <= 6){
                        startQuarter = sdf.format(firstDate).substring(0,4)+"年2季度";
                    } else if (currentMonth >= 7 && currentMonth <= 9){
                        startQuarter = sdf.format(firstDate).substring(0,4)+"年3季度";
                    } else if (currentMonth >= 10 && currentMonth <= 12){
                        startQuarter = sdf.format(firstDate).substring(0,4)+"年4季度";
                    }
                    lastDate.setTime(endMonth);
                    Date downDate = lastDate.getTime();
                    if (currentMonth >= 1 && currentMonth <= 3){
                        endQuarter = sdf.format(downDate).substring(0,4)+"年1季度";
                    }else if (currentMonth >= 4 && currentMonth <= 6){
                        endQuarter = sdf.format(downDate).substring(0,4)+"年2季度";
                    } else if (currentMonth >= 7 && currentMonth <= 9){
                        endQuarter = sdf.format(downDate).substring(0,4)+"年3季度";
                    } else if (currentMonth >= 10 && currentMonth <= 12){
                        endQuarter = sdf.format(downDate).substring(0,4)+"年4季度";
                    }
                    String lastQuarter = "";
                    while ( !startQuarter.equals(lastQuarter)){
                        int eYear = Integer.valueOf(endQuarter.substring(0, 4));
                        int eQuarter = Integer.valueOf(endQuarter.substring(5, 6));
                        endQuarter = eYear+ "年" + eQuarter + "季度";
                        if( !endQuarter.equals(startQuarter)){
                            if(eQuarter == 1){
                                eYear--;
                                eQuarter = 4;
                            }else {
                                eQuarter--;
                            }
                        }
                        lastQuarter = eYear + "年" + eQuarter + "季度";
                        double current = 0;
                        double last = 0;
                        Map<String,Object> map = new HashMap<>();
                        for(Map<String,Object> dataMap : dataList){
                            if(dataMap.get(dimension) != null){
                                String val = dataMap.get(dimension).toString();
                                if(val.equals(endQuarter) ){
                                    map.put(firstColumnField, endQuarter);
                                    map.put(dimension, endQuarter);
                                    current = Double.valueOf(dataMap.get(resultField).toString());
                                }
                                if(val.equals(lastQuarter) ){
                                    last = Double.valueOf(dataMap.get(resultField).toString());
                                }
                            }
                        }
                        if(last == 0){
                            map.put(resultField,"--");
                        }else {
                            double precent = (current - last)/last*100;
                            if(precent == 0){
                                map.put(resultField,0);
                            }else {
                                map.put(resultField,precent-0 ==0 ? 0 : basesicUtil.decimalPointHandle(precent));
                            }
                        }
                        resultList.add(map);
                        endQuarter = lastQuarter;
                    }
                }else if(dateType.toLowerCase().equals("month")){
                    String starthMonthStr = sdf.format(firstMonth).substring(0,7);
                    String endMonthStr = sdf.format(endMonth).substring(0,7);
                    while ( !starthMonthStr.equals(endMonthStr)){
                        double current = 0;
                        double last = 0;
                        Map<String,Object> map = new HashMap<>();
                        String nowMonthStr = endMonthStr;
                        String lastMontStr = "";
                        if( !starthMonthStr.equals(endMonthStr)){
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(sdf.parse(endMonthStr + "-01"));
                            calendar.add(Calendar.MONTH, -1);//当前时间前去一个月,即一个月前的时间
                            lastMontStr = sdf.format(calendar.getTime()).substring(0,7);
                        }else {
                            lastMontStr = starthMonthStr;
                        }
                        for(Map<String,Object> dataMap : dataList){
                            if(dataMap.get(dimension) != null){
                                String val = dataMap.get(dimension).toString();
                                if(val.equals(nowMonthStr) ){
                                    map.put(firstColumnField, val);
                                    map.put(dimension, val);
                                    current = Double.valueOf(dataMap.get(resultField).toString());
                                }
                                if(val.equals(lastMontStr) ){
                                    last = Double.valueOf(dataMap.get(resultField).toString());
                                }
                            }
                        }
                        if(last == 0){
                            map.put(resultField,"--");
                        }else {
                            double precent = (current - last)/last*100;
                            if(precent == 0){
                                map.put(resultField,0);
                            }else {
                                map.put(resultField,precent-0 ==0 ? 0 : basesicUtil.decimalPointHandle(precent));
                            }
                        }
                        resultList.add(map);
                        endMonthStr = lastMontStr;
                    }
                }
            }
            if(resultList != null ){
                Collections.reverse(resultList); // 倒序排列
            }
            return resultList;
        }
    }
    public String filtersExchangeHandle(String filters, EsConfig esConfig) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String otherFilter = "";
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
        String firstDay = sdf.format(lastDate.getTime());
        lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(lastDate.getTime());
        lastDate.add(Calendar.MONTH, -1);
        lastDate.set(Calendar.DAY_OF_MONTH, 1);
        String preMonthFirstDay = sdf.format(lastDate.getTime());
        lastDate.set(Calendar.DAY_OF_MONTH, lastDate.getActualMaximum(Calendar.DAY_OF_MONTH));
        String preMonthLastDay = sdf.format(lastDate.getTime());
        if (StringUtils.isNotEmpty(filters)) {
            String[] split = filters.split("and");
            for (String s : split) {
                // 拼接非quotaDate的过滤条件
                if (!s.contains(quotaDateField)) {
                    otherFilter += s + " and ";
                }
            }
        }
        // 如果有时间过滤条件,则计算时间条件计算
        if (StringUtils.isNotEmpty(filters) && filters.contains(quotaDateField)) {
            Calendar cal = Calendar.getInstance();
            boolean b = filters.indexOf("'") > -1;
            int start = b ? filters.indexOf("'") : filters.indexOf("\"");
            String condition = filters.substring(start + 1, start + 5); // 获取年份
            int year = Integer.parseInt(condition);
            String condition2 = filters.substring(filters.indexOf("-") + 1, filters.indexOf("-") + 3);  // 获取月份
            int month = Integer.parseInt(condition2);
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month - 1);
            cal.set(Calendar.DAY_OF_MONTH, 1); // 设置为1号,当前日期既为本月第一天
            firstDay = sdf.format(cal.getTime());
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            lastDay = sdf.format(cal.getTime());
            cal.add(Calendar.MONTH, -1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            preMonthFirstDay = sdf.format(cal.getTime());
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            preMonthLastDay = sdf.format(cal.getTime());
        }
        if ("1".equals(esConfig.getIncrementFlag())) {
            // 上月
            filters = "quotaDate >= '" + preMonthFirstDay + "' and quotaDate <= '" + preMonthLastDay + "'";
        } else if ("2".equals(esConfig.getIncrementFlag())) {
            // 当前月
            filters = "quotaDate >= '" + firstDay + "' and quotaDate <= '" + lastDay + "'";
        }
        if (StringUtils.isNotEmpty(esConfig.getFilter())) {
            filters += " and " + esConfig.getFilter();
        }
        if (StringUtils.isNotEmpty(otherFilter)) {
            filters = otherFilter + filters;
        }
        return filters;
    }
    public Double caculateResult(List<Map<String, Object>> listMap) {
        Map<String, Double> map = new HashMap<>();
        map.put("result", 0d);
        listMap.forEach(item -> {
            item.forEach((k,v) -> {
                if ("result".equals(k)) {
                    map.put("result", map.get("result") + Double.parseDouble(v + ""));
                }
            });
        });
        return map.get("result");
    }
    public Envelop searchEsByParam(String eventType, String time, Integer month) {
        Envelop envelop = new Envelop();
        String start = "", end = "";
        StringBuffer sb = new StringBuffer();
        List<String> xData = new ArrayList<>(); // x轴坐标
        List<Map<String, Object>> yData = new ArrayList<>(); // x轴坐标对应的值
        // 设置查询时间范围
        if (StringUtils.isNotEmpty(time)) {
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd'T'23:59:59'Z'");
            Date dateTime = DateUtil.strToDate(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateTime);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            end = dfs.format(calendar.getTime());
            calendar.add(Calendar.MONTH, -(month - 1));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            start = DateUtil.utcToDate(calendar.getTime());
        }
        if ("0".equals(eventType)) {
            sb.append("SELECT count(*) FROM medical_service_index where quotaCode='HC041100' and slaveKey1=0 and quotaDate>='")
                    .append(start).append("' and quotaDate<='").append(end).append("' group by date_histogram(field='quotaDate', 'interval'='month')");
        } else if ("1".equals(eventType)) {
            sb.append("SELECT count(*) FROM medical_service_index where quotaCode='HC041103' and quotaDate>='")
                    .append(start).append("' and quotaDate<='").append(end).append("' group by date_histogram(field='quotaDate', 'interval'='month')");
        }
        log.info(sb.toString());
        List<Map<String, Object>> list = elasticsearchUtil.excuteDataModel(sb.toString());
        list.forEach(one -> {
            xData.add((one.get("date_histogram(field=quotaDate,interval=month)") + "").substring(0,7));
            Map<String, Object> map = new HashMap<>();
            map.put((one.get("date_histogram(field=quotaDate,interval=month)") + "").substring(0,7), one.get("COUNT(*)"));
            yData.add(map);
        });
        return MixEnvelop.getSuccess("",xData,yData);
    }
}

+ 63 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/DeviceService.java

@ -0,0 +1,63 @@
package com.yihu.jw.basic.quota.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
/**
 * @Author: zdm
 * @Date: 2018/5/10
 * @Description: 设备一览
 */
@Service
@Transactional
public class DeviceService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * @param year  设备购买年份
     * @param district  区县
     * @param organization  机构
     * @param page  当前页
     * @param size  分页大小
     * @return
     */
    public List<Map<String, Object>> listMQcDeviceByYearAndDistrictAndOrg(String year, String district, String organization, int page , int size)throws Exception{
       String districtSql= district == null? "": "AND a.administrativeDivision='"+district+"' ";
       String organizationSql=organization == null ? "":"AND (a.orgCode LIKE '%"+organization+"%' " + "OR a.orgName LIKE '%"+organization+"%') ";
       String sql="SELECT a.*,sde.value AS deviceTypeName FROM (SELECT   " +
                "d.id AS id, " +
                "o.org_code AS orgCode, " +
                "o.full_name AS orgName, " +
                "o.administrative_division AS administrativeDivision, " +
                "o.hos_type_id AS hosTypeId, " +
                "d.device_name AS deviceName, " +
                "d.device_type AS deviceType, " +
                "d.purchase_num AS purchaseNum, " +
                "CASE d.origin_place WHEN 1 THEN '进口' WHEN 2 THEN '国产/合资' END AS originPlace, " +
                "d.manufacturer_name AS manufacturerName, " +
                "d.device_model AS deviceModel, " +
                "d.purchase_time AS purchaseTime, " +
                "CASE d.is_new WHEN 1 THEN '新设备' WHEN 2 THEN '二手设备' END AS isNew, " +
                "d.device_price AS devicePrice, " +
                "d.year_limit AS yearLimit, " +
                "CASE d.status WHEN 1 THEN '启用' WHEN 2 THEN '未启用' WHEN 3 THEN '报废' END AS status, " +
                "CASE d.is_gps WHEN 1 THEN '是' WHEN  0 THEN '否'END AS isGps " +
                "FROM device d,organizations o " +
                "WHERE d.org_code=o.org_code) a " +
                "LEFT JOIN system_dict_entries sde " +
                "ON a.deviceType = sde.code WHERE sde.dict_id='181' " + districtSql + organizationSql +
                "AND LEFT(a.purchaseTime,4)='"+year+"' ORDER BY a.purchaseTime DESC";
       sql += " limit "+(page-1)*size+" ,"+size;
        return jdbcTemplate.queryForList(sql);
    }
}

+ 265 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/OrgHealthCategoryStatisticsService.java

@ -0,0 +1,265 @@
package com.yihu.jw.basic.quota.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.quota.model.SaveModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 卫生机构类别统计 Service
 *
 * @author 张进军
 * @date 2017/12/26 13:42
 */
@Service
public class OrgHealthCategoryStatisticsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 将卫生机构类别末节点统计结果,填充到卫生机构类别集合中,
     * 然后合计父节点的统计结果。
     *
     * @param endpointsStatisticList 卫生机构类别末节点统计结果
     * @return 所有卫生机构类别的统计结果
     */
    public List<SaveModel> getAllNodesStatistic(List<Map<String, Object>> endpointsStatisticList) {
        // 获取所有卫生机构类别的集合
        String sql = "SELECT id, pid, top_pid AS topPid, code, name, 0 AS result, 'false' AS isEndpoint FROM org_health_category ORDER BY code ";
        List<Map<String, Object>> allOrgHealthCategoryList = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> endpoint : endpointsStatisticList) {
            for (int i = 0, len = allOrgHealthCategoryList.size(); i < len; i++) {
                Map<String, Object> item = allOrgHealthCategoryList.get(i);
                if (item.get("code").toString().equals(endpoint.get("code").toString())) {
                    // 填充末节点统计结果
                    item.put("result", endpoint.get("result"));
                    item.put("isEndpoint", "true");
                }
                item.put("town", endpoint.get("town"));
                item.put("townName", endpoint.get("townName"));
                item.put("year", endpoint.get("year"));
                item.put("yearName", endpoint.get("yearName"));
                item.put("slaveKey1", endpoint.get("slaveKey1"));
                item.put("slaveKey1Name", endpoint.get("slaveKey1Name"));
                item.put("slaveKey2", endpoint.get("slaveKey2"));
                item.put("slaveKey2Name", endpoint.get("slaveKey2Name"));
                item.put("slaveKey3", endpoint.get("slaveKey3"));
                item.put("slaveKey3Name", endpoint.get("slaveKey3Name"));
                if(endpoint.get("economic") != null){
                    item.put("economic", endpoint.get("economic"));
                    item.put("economicName", endpoint.get("economicName"));
                }
                if(endpoint.get("level") != null){
                    item.put("level", endpoint.get("level"));
                    item.put("levelName", endpoint.get("levelName"));
                }
            }
        }
        // 合计父节点统计结果
        for (int j = 0, jLen = allOrgHealthCategoryList.size(); j < jLen; j++) {
            Map<String, Object> item = allOrgHealthCategoryList.get(j);
            int id = (int) item.get("id");
            List<Map<String, Object>> itemEndpointList = findEndpointsForOneParent(allOrgHealthCategoryList, id);
            if (itemEndpointList.size() != 0) {
                item.put("result", countResult(itemEndpointList));
            }
        }
        return translateModel(endpointsStatisticList, allOrgHealthCategoryList);
    }
    /**
     * 查找指定父节点的所有末节点
     *
     * @param allOrgHealthCategoryList 所有卫生机构类集合
     * @param pid                      指定的父节点ID
     * @return 指定父节点的所有末节点集合
     */
    private List<Map<String, Object>> findEndpointsForOneParent(List<Map<String, Object>> allOrgHealthCategoryList, int pid) {
        List<Map<String, Object>> endpointList = new ArrayList<>();
        for (Map<String, Object> item : allOrgHealthCategoryList) {
            int id = (int) item.get("id");
            Object itemPid = item.get("pid");
            boolean isEndpoint = Boolean.parseBoolean(item.get("isEndpoint").toString());
            if (itemPid == null && id == pid) { // 顶节点
                List<Map<String, Object>> topPointList = new ArrayList<>();
                for (Map<String, Object> topSubItem : allOrgHealthCategoryList) {
                    Object topPid = topSubItem.get("topPid");
                    Object topSubItemPid = topSubItem.get("pid");
                    boolean isEndpointSubItem = Boolean.parseBoolean(topSubItem.get("isEndpoint").toString());
                    if (topSubItemPid != null && Integer.parseInt(topPid.toString()) == pid && isEndpointSubItem) {
                        topPointList.add(topSubItem);
                    }
                }
                return topPointList;
            } else if (itemPid != null && (int) itemPid == pid) {
                if (isEndpoint) {
                    endpointList.add(item);
                } else {
                    endpointList.addAll(findEndpointsForOneParent(allOrgHealthCategoryList, id));
                }
            }
        }
        return endpointList;
    }
    /**
     * 合计指定卫生机构类别末节点集合中的统计结果
     *
     * @param endpointList 卫生机构类别末节点集合
     * @return 合计的统计值
     */
    private int countResult(List<Map<String, Object>> endpointList) {
        return endpointList.stream()
                .mapToInt(item -> item.get("result") != null ? Integer.parseInt(item.get("result").toString()) : 0)
                .sum();
    }
    /**
     * 将卫生机构类别统计结果转换成 SaveModel
     *
     * @param endpointsStatisticList   卫生机构类别末节点统计结果
     * @param allOrgHealthCategoryList 所有卫生机构类集合
     * @return
     */
    private List<SaveModel> translateModel(List<Map<String, Object>> endpointsStatisticList,
                                           List<Map<String, Object>> allOrgHealthCategoryList) {
        List<SaveModel> resultList = new ArrayList<>();
        try {
            String quotaCode = null;
            String quotaName = null;
            String quotaDate = null;
            String town = null;
            String year = null;
            String slaveKey1 = null;
            String slaveKey2 = null;
            String slaveKey3 = null;
            String townName = null;
            String yearName = null;
            String slaveKey1Name = null;
            String slaveKey2Name = null;
            String slaveKey3Name = null;
            String economic = null;
            String economicName = null;
            String level = null;
            String levelName = null;
            if (endpointsStatisticList.size() > 0) {
                Map<String, Object> endpoint = endpointsStatisticList.get(0);
                quotaCode = endpoint.get("quotaCode").toString().replaceAll("_", "");
                quotaName = endpoint.get("quotaName").toString();
                quotaDate = endpoint.get("quotaDate").toString();
            }
            SaveModel model;
            for (Map<String, Object> item : allOrgHealthCategoryList) {
                model = new SaveModel();
                town = item.get("town") == null ? null : item.get("town").toString();
                year = item.get("year") == null ? null : item.get("year").toString();
                slaveKey1 = item.get("slaveKey1") == null ? null : item.get("slaveKey1").toString();
                slaveKey2 = item.get("slaveKey2") == null ? null : item.get("slaveKey2").toString();
                slaveKey3 = item.get("slaveKey3") == null ? null : item.get("slaveKey3").toString();
                townName = item.get("townName") == null ? null : item.get("townName").toString();
                yearName = item.get("yearName") == null ? null : item.get("yearName").toString();
                slaveKey1Name = item.get("slaveKey1Name") == null ? null : item.get("slaveKey1Name").toString();
                slaveKey2Name = item.get("slaveKey2Name") == null ? null : item.get("slaveKey2Name").toString();
                slaveKey3Name = item.get("slaveKey3Name") == null ? null : item.get("slaveKey3Name").toString();
                economic = item.get("economic") == null ? null : item.get("economic").toString();
                economicName = item.get("economicName") == null ? null : item.get("economicName").toString();
                level = item.get("level") == null ? null : item.get("level").toString();
                levelName = item.get("levelName") == null ? null : item.get("levelName").toString();
                model.setQuotaCode(quotaCode);
                model.setQuotaName(quotaName);
                model.setQuotaDate(quotaDate);
                model.setTown(town);
                model.setTownName(townName);
                model.setYear(year);
                model.setYearName(yearName);
                model.setSlaveKey1(slaveKey1);
                model.setSlaveKey2(slaveKey2);
                model.setSlaveKey3(slaveKey3);
                model.setSlaveKey1Name(slaveKey1Name);
                model.setSlaveKey2Name(slaveKey2Name);
                model.setSlaveKey3Name(slaveKey3Name);
                model.setEconomic(economic);
                model.setEconomicName(economicName);
                model.setLevel(level);
                model.setLevelName(levelName);
                model.setCreateTime(new Date());
                model.setOrgHealthCategoryId(item.get("id").toString());
                String pid = item.get("pid") == null ? null : item.get("pid").toString();
                model.setOrgHealthCategoryPid(pid);
                String code = item.get("code") == null ? null : item.get("code").toString();
                model.setOrgHealthCategoryCode(code);
                model.setOrgHealthCategoryName(item.get("name").toString());
                model.setResult(item.get("result").toString());
                resultList.add(model);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    /**
     * 根据父级ID,递归获取卫生机构类别的父级及其子级集合,形成树形结构。
     *
     * @param pid 父级ID,为 -1 时获取整棵树。
     * @return 父级及其子集的树形结构数据
     */
    public List<Map<String, Object>> getOrgHealthCategoryTreeByPid(int pid) {
        List<Map<String, Object>> treeList = new ArrayList<>();
        List<Map<String, Object>> childList = new ArrayList<>();
        if (pid == -1) {
            childList = getOrgHealthCategoryTopNodes();
        } else {
            childList = getOrgHealthCategoryChildrenByPid(pid);
        }
        for (Map<String, Object> child : childList) {
            child.put("children", getOrgHealthCategoryTreeByPid((int) child.get("id")));
            treeList.add(child);
        }
        return treeList;
    }
    /**
     * 根据ID,获取卫生机构类别信息
     */
    private Map<String, Object> getOrgHealthCategoryById(int id) {
        String sql = "SELECT o.id, o.pid, o.code, o.name AS text, NULL AS children FROM org_health_category o WHERE o.id = " + id;
        return (Map<String, Object>) jdbcTemplate.queryForMap(sql);
    }
    /**
     * 获取卫生机构类别顶级节点
     */
    private List<Map<String, Object>> getOrgHealthCategoryTopNodes() {
        String sql = "SELECT o.id, o.pid, o.code, o.name AS text, NULL AS children FROM org_health_category o WHERE o.pid IS NULL";
        return (List<Map<String, Object>>) jdbcTemplate.queryForList(sql);
    }
    /**
     * 根据卫生机构类别父级点ID,获取其子节点集合
     */
    private List<Map<String, Object>> getOrgHealthCategoryChildrenByPid(int pid) {
        String sql = "SELECT o.id, o.pid, o.code, o.name AS text, NULL AS children FROM org_health_category o WHERE o.pid = " + pid;
        return (List<Map<String, Object>>) jdbcTemplate.queryForList(sql);
    }
}

+ 292 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/QuotaService.java

@ -0,0 +1,292 @@
package com.yihu.jw.basic.quota.service;
import com.yihu.jw.basic.es.EsResultExtract;
import com.yihu.jw.basic.quota.dao.XTjQuotaRepository;
import com.yihu.jw.basic.resource.service.RsResourceQuotaService;
import com.yihu.jw.basic.util.BasesicUtil;
import com.yihu.jw.entity.ehr.quota.TjQuota;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
/**
 * @author janseny
 */
@Service
public class QuotaService {
    @Autowired
    private XTjQuotaRepository quotaDao;
    @Autowired
    private EsResultExtract esResultExtract;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RsResourceQuotaService resourceQuotaService;
    @Autowired
    private OrgHealthCategoryStatisticsService orgHealthCategoryStatisticsService;
    @Autowired
    private BaseStatistsService baseStatistsService;
    @Autowired
    private DeviceService deviceService;
    private BasesicUtil basesicUtil = new BasesicUtil();
    public static String orgHealthCategoryCode = "orgHealthCategoryCode";
    public List<Map<String, Object>> getQuotaReportTwoDimensionalTable(String quotaCodeStr, String filter,String dimension, String top
    ) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> quotaViewResult = new HashMap<>();
        List<String> quotaCodes = Arrays.asList(quotaCodeStr.split(","));
        String maxQuotaCode = "";
        int num = 0;
        try {
            for (String code : quotaCodes) {
                List<Map<String, Object>> quotaResult = baseStatistsService.getSimpleQuotaReport(code, filter, dimension,false, top);
                if (quotaResult.size() >= num) {
                    num = quotaResult.size();
                    maxQuotaCode = code;
                }
                quotaViewResult.put(code, quotaResult);
            }
            Map<String, List<Map<String, Object>>> otherQuotaViewResult = new HashMap<>();
            for (String key : quotaViewResult.keySet()) {
                if (key != maxQuotaCode) {
                    otherQuotaViewResult.put(key, quotaViewResult.get(key));
                }
            }
            //以查询结果数据最多的指标为主,其他指标对应维度没有数据的补充0
            for (Map<String, Object> vMap : quotaViewResult.get(maxQuotaCode)) {
                vMap.put(maxQuotaCode, vMap.get("result")==null ? 0 : ("--".equals(vMap.get("result")) ? vMap.get("result") : basesicUtil.decimalPointHandle(Double.valueOf(vMap.get("result").toString()))));
                for (String viewQuotaCode : otherQuotaViewResult.keySet()) {
                    if(otherQuotaViewResult != null && otherQuotaViewResult.get(viewQuotaCode) != null && otherQuotaViewResult.get(viewQuotaCode).size()>0 ){
                        for (Map<String, Object> quotaResultMap : otherQuotaViewResult.get(viewQuotaCode)) {
                            if (quotaResultMap.get(dimension) != null && vMap.get(dimension) != null ) {
                                if (vMap.get(dimension).toString().trim().equals(quotaResultMap.get(dimension).toString().trim())) {
                                    vMap.put(viewQuotaCode, quotaResultMap.get("result")==null ? 0 : ("--".equals(quotaResultMap.get("result")) ? quotaResultMap.get("result") : basesicUtil.decimalPointHandle(Double.valueOf(quotaResultMap.get("result").toString()))));
                                    break;
                                } else {
                                    if( !vMap.get(dimension).toString().equals("合计")){
                                        vMap.put(viewQuotaCode, 0);
                                    }
                                }
                            } else {
                                vMap.put(viewQuotaCode, 0);
                            }
                        }
                    }else {
                        vMap.put(viewQuotaCode, 0);
                    }
                }
            }
            List<Map<String, Object>> resultList = quotaViewResult.get(maxQuotaCode);
            if(dimension.equals(orgHealthCategoryCode)){//如果是特殊机构类型树状机构需要转成树状结构
                List<Map<String, Object>> orgHealthCategoryList = orgHealthCategoryStatisticsService.getOrgHealthCategoryTreeByPid(-1);
//                dataList = baseStatistsService.setResultAllDimenMap(maxQuotaCode, orgHealthCategoryList, resultList,null);
                //采用新的
                dataList = baseStatistsService.allCategoryResultMap(quotaCodes, orgHealthCategoryList, resultList);
            }else {
                dataList = resultList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for(Map<String, Object> map : dataList){
            if(map.get("firstColumn") == null || map.get("firstColumn").toString().equals("null") || StringUtils.isEmpty(map.get("firstColumn").toString())){
                if(map.get("level")!= null && StringUtils.isNotEmpty(map.get("level").toString())){
                    String level = map.get("level").toString();
                    if (level.equals("1")){
                        level = "一级";
                    }else if (level.equals("2")){
                        level = "二级";
                    }else if (level.equals("3")){
                        level = "三级";
                    }else {
                        level = "未指定";
                    }
                    map.put("firstColumn",level);
                }
                if(map.get("economic")!= null && StringUtils.isNotEmpty(map.get("economic").toString())){
                    String economic = map.get("economic").toString();
                    if (economic.equals("1021")){
                        economic = "公立";
                    }else if (economic.equals("1022")){
                        economic = "非公立";
                    }else {
                        economic = "其他";
                    }
                    map.put("firstColumn",economic);
                }
            }
        }
        //计算合计
        if(dataList != null && dataList.size() > 0){
            Map<String, Object> sumMap = new HashMap<>();
            sumMap.put("firstColumn","合计");
            for (String code : quotaCodes) {
                String total =  existsTotal(code,dataList);
                if( total.equals("false") || total.equals("--")){
                    double sum = 0;
                    sum = calculateSum(sum,code,dataList);
                    sumMap.put(code, basesicUtil.decimalPointHandle(sum));
                }else {
                    sumMap.put(code, basesicUtil.decimalPointHandle(Double.valueOf(total)));
                }
            }
            dataList.add(0,sumMap);
            if(dataList.get(dataList.size()-1).get("firstColumn") != null){
                if(dataList.get(dataList.size()-1).get("firstColumn").equals("合计")){
                    dataList.remove(dataList.size()-1);
                }
            }
        }
        int size = dataList.size();
        if (size > 0 && dataList.get(size - 1).containsValue("合计")) {
            dataList = dataList.subList(0, size - 1);
        }
        return dataList;
    }
    /**
     * 判断指标统计中 总计 是否已经计算过
     * @param code
     * @param dataList
     * @return
     */
    private String existsTotal(String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get("firstColumn") != null && map.get("firstColumn").toString().equals("合计") && map.get(code) != null){
                if(map.get(code).toString().equals("--")){
                    return "false";
                }else {
                    return map.get(code).toString();
                }
            }
        }
        return "false";
    }
    /**
     * 统计每列合计
     * @param sum
     * @param code
     * @param dataList
     * @return
     */
    private double calculateSum( double sum,String code,List<Map<String, Object>> dataList){
        for(Map<String, Object> map : dataList){
            if(map.get(code) != null){
                sum += Double.valueOf("--".equals(map.get(code)) ? "0" : map.get(code).toString());
            }
        }
        return sum;
    }
    public TjQuota findOne(Long id){
        return quotaDao.getOne(id);
    }
    public TjQuota findByCode(String code){
        return quotaDao.findByCode(code);
    }
    public List<Map<String, Object>> queryResultPage(Long id,String filters ,int pageNo,int pageSize) throws Exception {
        TjQuota tjQuota= quotaDao.getOne(id);
        return  esResultExtract.queryResultPage(tjQuota, filters, pageNo, pageSize);
    }
    public List<Map<String, Object>> queryResultPageByCode(String code,String filters ,int pageNo,int pageSize) throws Exception {
        TjQuota tjQuota= quotaDao.findByCode(code);
        return  esResultExtract.queryResultPage(tjQuota, filters, pageNo, pageSize);
    }
    public long getQuotaTotalCount(Long id,String filters) throws Exception {
        TjQuota tjQuota= quotaDao.getOne(id);
        long count = esResultExtract.getQuotaTotalCount(tjQuota,filters);
        return count;
    }
    //指标分组统计数量 - 只支持一个字段
    public List<Map<String, Object>> searcherByGroup(TjQuota tjQuota,String filters,String aggsField ) throws Exception {
        return  esResultExtract.searcherByGroup(tjQuota, filters,aggsField );
    }
    //根据mysql 指标分组求和 支持一个和多个字段
    public Map<String, Integer> searcherSumByGroupBySql(TjQuota tjQuota,String aggsField ,String filters,String sumField ,String orderFild,String order) throws Exception {
        return  esResultExtract.searcherSumByGroupBySql(tjQuota, aggsField, filters,sumField,orderFild,order);
    }
    //多维度数据的总和 返回数据结果集
    //返回结果 :key为共同维度的组合值,value为数据结果集
    public Map<String,Map<String, Object>> getQuotaResult(Long id, String filters,String dimension) throws Exception {
        String[] dimensions = null;
        if(StringUtils.isNotEmpty(dimension)){
            dimensions = dimension.split(";");
        }else{
            dimensions = new String[]{"quotaDate"};
        }
        TjQuota tjQuota= quotaDao.getOne(id);
        List<Map<String, Object>> resultListMap = esResultExtract.getQuotaReport(tjQuota, filters,10000);
        Map<String,Map<String, Object>> cloumnMap = new HashMap<>();
        for(int i=0 ; i < resultListMap.size() ;i++){
            Map<String, Object> resultMap = resultListMap.get(i);
            Object resultVal = resultMap.get("result");
            String cloumnStr = "";//多个列 值 拼接串
            for(int k=0 ; k < dimensions.length ; k++){
                String nameVal = resultMap.get(dimensions[k]).toString();
                cloumnStr = cloumnStr + nameVal + "-";
            }
            boolean repeat = false;
            Object oldResultVal = null;
            if( cloumnMap.size() == 0 ){//第一个
                cloumnMap.put(cloumnStr,resultMap);
            }else {
                for(String key:cloumnMap.keySet()){
                    if(cloumnStr.equals(key)){
                        repeat = true;
                        Map<String, Object> oldMap = cloumnMap.get(key);
                        oldResultVal = oldMap.get("result");
                    }
                }
            }
            if( !repeat){
                cloumnMap.put(cloumnStr,resultMap);
            }else {
                //如果有重复 先计删除listl里面的数据,再添加新数据
                cloumnMap.remove(cloumnStr);
                resultMap.remove("result");
                Object newResultVal = ( Integer.valueOf(resultVal.toString()) + Integer.valueOf(oldResultVal.toString()) );
                resultMap.put("result",newResultVal);
                cloumnMap.put(cloumnStr, resultMap);
            }
        }
        return cloumnMap;
    }
}

+ 901 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/SingleDiseaseService.java

@ -0,0 +1,901 @@
package com.yihu.jw.basic.quota.service;
import com.yihu.jw.basic.es.util.ElasticsearchUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
/**
 * Created by wxw on 2018/2/27.
 */
@Service
public class SingleDiseaseService {
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static final Logger log = LoggerFactory.getLogger(SingleDiseaseService.class);
    public static final String HEALTH_PROBLEM = "1"; // 健康问题
    public static final String AGE = "2"; // 年龄段分布
    public static final String SEX = "3"; // 性别
    /**
     * 热力图数据
     * @return
     * @throws Exception
     */
    public List<Map<String,String>>  getHeatMap(String condition) throws Exception {
        List<Map<String,String>> list = new ArrayList<>();
        String sql = "select addressLngLat from singleDiseasePersonal where addressLngLat is not null";
        if (!StringUtils.isEmpty(condition) && !condition.contains("undefined")) {
            sql += " and " + condition;
        }
        log.info("sql = " + sql);
        List<Map<String, Object>> listData = parseIntegerValue(sql);
        Map<String, Object> map = new HashMap<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(item -> {
                map.put(item.get("addressLngLat") + "", 1);
            });
            map.forEach((k,v)->{
                Map<String, String> temp = new HashMap<>();
                // "k":"116.419787;39.930658"
                String lng = k.split(";")[0];
                String lat = k.split(";")[1];
                temp.put("lng", lng);
                temp.put("lat", lat);
                temp.put("count", v + "");
                list.add(temp);
            });
        }
        return list;
    }
    /**
     * 获取糖尿病患者数
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getNumberOfDiabetes(String condition) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select town, count(*) from singleDiseasePersonal where town is not null");
        if (!StringUtils.isEmpty(condition)&& !condition.contains("undefined")) {
            sql.append(" and " + condition);
        }
        sql.append(" group by town");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> list = parseIntegerValue(sql.toString());
        List<Map<String, Object>> dataList = fillNoDataColumn(list);
        return dataList;
    }
    /**
     * 补全福州各个区县的患病人数
     * @param dataList
     * @return
     */
    private List<Map<String, Object>> fillNoDataColumn(List<Map<String, Object>> dataList) {
        String townSql = "SELECT id as town, name as townName from address_dict where pid = 350100";
        Map<String, Object> dictMap = new HashMap<>();
        List<Map<String, Object>> dictDataList = jdbcTemplate.queryForList(townSql);
        if(null != dictDataList) {
            for(int i = 0 ; i < dictDataList.size();i++){
                if(null != dictDataList.get(i).get("town") && null != dictDataList.get(i).get("townName")){
                    dictMap.put(dictDataList.get(i).get("town").toString(),dictDataList.get(i).get("townName").toString());
                }
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(String code : dictMap.keySet()){
            Map<String,Object> oneMap = new HashMap<>();
            String result = "0";
            for(Map<String,Object> map : dataList){
                if(map.get("town") != null && code.equals(map.get("town"))){
                    result = map.get("COUNT(*)").toString();
                    break;
                }
            }
            oneMap.put("townName",dictMap.get(code));
            oneMap.put("town",code);
            oneMap.put("result",result);
            resultList.add(oneMap);
        }
        return  resultList;
    }
    /**
     * 新增患者年趋势
     * @return
     */
    public Map<String, List<String>> getLineDataInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select eventDate, count(*) from singleDiseasePersonal");
        if (!StringUtils.isEmpty(condition)&& !condition.contains("undefined")) {
            sql.append(" where " + condition);
        }
        sql.append(" group by date_histogram(field='eventDate','interval'='year')");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> valueData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                // "date_histogram(field=eventDate,interval=year)":"2015-01-01 00:00:00",因为是获取年份,所以截取前4位
                xData.add((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4));
                valueData.add(one.get("COUNT(*)") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     * 获取饼状图数据
     * @param type 健康状况、年龄段、性别
     * @return
     */
    public Map<String, Object> getPieDataInfo(String type, String condition) {
        Map<String, Object> map = new HashMap<>();
        if(condition.contains("undefined")){
            condition = "";
        }
        if (HEALTH_PROBLEM.equals(type)) {
            map = getHealthProInfo(condition);
        } else if (AGE.equals(type)) {
            map = getAgeInfo(condition);
        } else if (SEX.equals(type)) {
            map = getGenderInfo(condition);
        }
        return map;
    }
    /**
     * 获取健康状况
     * @return
     */
    public Map<String, Object> getHealthProInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select diseaseTypeName,count(*) from singleDiseasePersonal");
        if (!StringUtils.isEmpty(condition)) {
            sql.append(" where " + condition);
        }
        sql.append(" group by diseaseTypeName");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, Object> map = new HashMap<>();
        List<String> legendData = new ArrayList<>();
        List<Map<String, Object>> seriesData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                Map<String, Object> myMap = new HashMap<>();
                legendData.add(one.get("diseaseTypeName") + "");
                myMap.put("name", one.get("diseaseTypeName") + "");
                myMap.put("value", one.get("COUNT(*)") + "");
                seriesData.add(myMap);
            });
            map.put("legendData", legendData);
            map.put("seriesData", seriesData);
        }
        return map;
    }
    /**
     * 获取年龄段数据
     * @return
     */
    public Map<String, Object> getAgeInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR) + 1;
        /*
        * 年龄段分为0-6、7-17、18-40、41-65、65以上
        * 首先获取当前年份,由于ES查询是左包含,右不包,所以当前年份需要+1
        * 下面为构造年龄段的算式,其中year-151限定了范围是66-150岁 即66以上,其他类似
        * */
        String range = "range(birthYear," + (year - 151) + "," + (year - 66) + "," + (year - 41) + "," + (year - 18) + "," + (year - 7) + "," + year + ")";
        sql.append("select count(*) from singleDiseasePersonal where birthYear <> 0");
        if (!StringUtils.isEmpty(condition)) {
            sql.append(" and " + condition);
        }
        sql.append(" group by " + range);
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, Object> map = new HashMap<>();
        List<String> legendData = new ArrayList<>();
        List<Map<String, Object>> seriesData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                String rangeName = one.get(range) + "";
                // rangeName:"1978.0-2001.0"
                int first = (int) Double.parseDouble(rangeName.split("-")[0]);
                int last = (int) Double.parseDouble(rangeName.split("-")[1]);
                Integer result = last - first;
                // 转成相应的年龄段
                String keyName = exchangeInfo(result);
                Map<String, Object> myMap = new HashMap<>();
                legendData.add(keyName);
                myMap.put("name", keyName);
                myMap.put("value", one.get("COUNT(*)") + "");
                seriesData.add(myMap);
            });
            map.put("legendData", legendData);
            map.put("seriesData", seriesData);
        }
        return map;
    }
    private String exchangeInfo(Integer result) {
        String keyName = "";
        switch (result) {
            case 85:
                keyName = "66岁以上";
                break;
            case 25:
                keyName = "41-65岁";
                break;
            case 23:
                keyName = "18-40岁";
                break;
            case 11:
                keyName = "7-17岁";
                break;
            case 7:
                keyName = "0-6岁";
                break;
            default:
                break;
        }
        return keyName;
    }
    /**
     * 获取性别数据
     * @return
     */
    public Map<String, Object> getGenderInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select sexName, count(*) from singleDiseasePersonal");
        if (!StringUtils.isEmpty(condition)) {
            sql.append(" where " + condition);
        }
        sql.append(" group by sexName");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, Object> map = new HashMap<>();
        List<String> legendData = new ArrayList<>();
        List<Map<String, Object>> seriesData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                Map<String, Object> myMap = new HashMap<>();
                legendData.add(one.get("sexName") + "");
                myMap.put("name", one.get("sexName") + "");
                myMap.put("value", one.get("COUNT(*)") + "");
                seriesData.add(myMap);
            });
            map.put("legendData", legendData);
            map.put("seriesData", seriesData);
        }
        return map;
    }
    /**
     * 获取并发症数据
     * @return
     */
    public Map<String, List<String>> getSymptomDataInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select symptomName, count(*) from singleDiseaseCheck where checkCode = 'CH001'");
        if (!StringUtils.isEmpty(condition)) {
            sql.append(" and " + condition);
        }
        sql.append(" group by symptomName");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> valueData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                xData.add(one.get("symptomName") + "");
                valueData.add(one.get("COUNT(*)") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     * 用药患者数分布
     * @return
     */
    public Map<String, List<String>> getMedicineDataInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select medicineName, count(*) from singleDiseaseCheck where checkCode = 'CH004'");
        if (!StringUtils.isEmpty(condition)) {
            sql.append(" and " + condition);
        }
        sql.append(" group by medicineName");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> listData = parseIntegerValue(sql.toString());
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> valueData = new ArrayList<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            listData.forEach(one -> {
                xData.add(one.get("medicineName") + "");
                valueData.add(one.get("COUNT(*)") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     *  空腹血糖统计
     * @return
     */
    public Map<String, List<String>> getFastingBloodGlucoseDataInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select fastingBloodGlucoseCode, count(*) from singleDiseaseCheck where checkCode = 'CH002'");
        if (!StringUtils.isEmpty(condition) && !condition.contains("undefined")) {
            //先把过滤条件忽略性别的过滤
            condition = changeCondition(condition);
            sql.append(" and " + condition);
        }
        sql.append(" group by fastingBloodGlucoseCode");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> list = parseIntegerValue(sql.toString());
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new LinkedList<>();
        // 获取横坐标
        xData.add("4.4~6.1mmol/L");
        xData.add("6.1~7mmol/L");
        xData.add("7.0mmol/L以上");
        Map<String,String> resultDataMap = new HashMap<>();
//        if (null != list && list.get(0).size() > 0) {
//            list.forEach(one -> {
//                String code =  one.get("fastingBloodGlucoseCode") + "";
//                String count = one.get("COUNT(*)") + "";
//                String gender = one.get("sexName") + "";
//                if(!code.equals("null") && StringUtils.isNotEmpty(code)){
//                    resultDataMap.put(code + "-"+ gender,count);
//                }
//                resultDataMap.put(code,count);
//            });
//
//            for(int i =1;i<4 ;i++){
//                if( !resultDataMap.containsKey(i + "-" + "男性")) {
//                    resultDataMap.put(i + "-" + "男性","0");
//                }
//                if( !resultDataMap.containsKey(i + "-" + "女性")) {
//                    resultDataMap.put(i + "-" + "女性","0");
//                }
//            }
//
//            List<String> valueData1 = new LinkedList<>();    // 存放第一个数据源 男生
//            List<String> valueData2 = new LinkedList<>();    // 存放第二个数据源 女生
//            map.put("xData", xData);
//            for(String key : resultDataMap.keySet()){
//                if(key.contains("男性")){
//                    valueData1.add(resultDataMap.get(key)+"");
//                }
//                if(key.contains("女性")){
//                    valueData2.add(resultDataMap.get(key)+"");
//                }
//            }
//            map.put("valueData1", valueData1);
//            map.put("valueData2", valueData2);
//        }
        //无性别输出
        List<String> valueData = new ArrayList<>();
        if (null != list && list.size() > 0 && list.get(0).size() > 0) {
            list.forEach(one -> {
                valueData.add(one.get("COUNT(*)") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     * 糖耐量统计
     * @return
     */
    public Map<String, List<String>> getSugarToleranceDataInfo(String condition) {
        StringBuffer sql = new StringBuffer();
        sql.append("select sugarToleranceCode, count(*) from singleDiseaseCheck where checkCode = 'CH003'");
        if (!StringUtils.isEmpty(condition) && !condition.contains("undefined")) {
            //先把过滤条件忽略性别的过滤
            condition = changeCondition(condition);
            sql.append(" and " + condition);
        }
        sql.append(" group by sugarToleranceCode");
        log.info("sql = " + sql.toString());
        List<Map<String, Object>> list = parseIntegerValue(sql.toString());
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new LinkedList<>();
        // 获取横坐标
        xData.add("7.8 mmol/L以下");
        xData.add("7.8~11.1 mmol/L");
        xData.add("11.1 mmol/L以上");
//        Map<String,String> resultDataMap = new HashMap<>();
//        if (null != list && list.get(0).size() > 0) {
//            list.forEach(one -> {
//                String code =  one.get("sugarToleranceCode") + "";
//                String gender = one.get("sexName") + "";
//                String count = one.get("COUNT(*)") + "";
//                if(!code.equals("null") && StringUtils.isNotEmpty(code)){
//                    resultDataMap.put(code + "-"+ gender,count);
//                }
//            });
//
//            for(int i =1;i<4 ;i++){
//                if( !resultDataMap.containsKey(i + "-" + "男性")) {
//                    resultDataMap.put(i + "-" + "男性","0");
//                }
//                if( !resultDataMap.containsKey(i + "-" + "女性")) {
//                    resultDataMap.put(i + "-" + "女性","0");
//                }
//            }
//
//            List<String> valueData1 = new LinkedList<>();    // 存放第一个数据源 男生
//            List<String> valueData2 = new LinkedList<>();    // 存放第二个数据源 女生
//            map.put("xData", xData);
//            for(String key : resultDataMap.keySet()){
//                if(key.contains("男性")){
//                    valueData1.add(resultDataMap.get(key)+"");
//                }
//                if(key.contains("女性")){
//                    valueData2.add(resultDataMap.get(key)+"");
//                }
//            }
//            map.put("valueData1", valueData1);
//            map.put("valueData2", valueData2);
//        }
        //无性别输出
        List<String> valueData = new ArrayList<>();
        if (null != list && list.size() > 0 && list.get(0).size() > 0) {
            list.forEach(one -> {
                valueData.add(one.get("COUNT(*)") + "");
            });
            map.put("xData", xData);
            map.put("valueData", valueData);
        }
        return map;
    }
    /**
     * 对查询结果key包含count、sum的value去掉小数点
     * @param sql
     * @return
     */
    public List<Map<String, Object>> parseIntegerValue(String sql) {
        List<Map<String, Object>> listData = elasticsearchUtil.excuteDataModel(sql);
        List<Map<String, Object>> handleData = new ArrayList<>();
        listData.forEach(item -> {
            Map<String, Object> myMap = new HashMap<>();
            item.forEach((k,v) -> {
                if (k.contains("COUNT") || k.contains("SUM")) {
                    v = (int) Double.parseDouble(v + "");
                }
                myMap.put(k,v);
            });
            handleData.add(myMap);
        });
        return handleData;
    }
    /**
     * 采集出来的空腹血糖和糖耐量用户的性别基本都是未知(状态为0),所以先忽略性别的过滤
     * @param condition
     * @return
     */
    private String changeCondition(String condition) {
        StringBuffer buffer = new StringBuffer();
        String[] ands = condition.split("and");
        for (String and : ands) {
            if (!and.contains("sex")) {
                buffer.append(and.trim() + " and ");
            }
        }
        String newCondition = buffer.toString();
        return newCondition.substring(0, newCondition.length() - 4).trim();
    }
    /**
     * 获取糖尿病类型分析
     * @param type
     * @param filter
     * @return
     */
    public Map<String, List<String>> getDiseaseTypeAnalysisInfo(String type, String filter) {
        String sql = "";
        if ("1".equals(type)) {
            sql = "select count(*) from singleDiseasePersonal group by diseaseTypeName,date_histogram(field='eventDate','interval'='year') order by eventDate,diseaseType";
        } else {
            if(filter.isEmpty()){
                sql = "select count(*) from singleDiseasePersonal group by diseaseTypeName,date_histogram(field='eventDate','interval'='month')";
            }else {
                sql = "select count(*) from singleDiseasePersonal  where " + filter + " group by diseaseTypeName,date_histogram(field='eventDate','interval'='month')";
            }
        }
        log.info("sql = " + sql);
        List<Map<String, Object>> listData = parseIntegerValue(sql);
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> valueData = new ArrayList<>();
        Set<String> hashSet = new TreeSet<>();
        Map<String, String> value = new HashMap<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            if ("1".equals(type)) {
                listData.forEach(one -> {
                    hashSet.add((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4));
                    value.put((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4) + "-"+ one.get("diseaseTypeName"), one.get("COUNT(*)") + "");
                });
            } else {
                hashSet.clear();
                hashSet.addAll(getMonthInfo());
                listData.forEach(one -> {
                    value.put((one.get("date_histogram(field=eventDate,interval=month)") + "").substring(5,7) + "-"+ one.get("diseaseTypeName"), one.get("COUNT(*)") + "");
                });
            }
        }
        List<String> name = new ArrayList<>();
        name.add("I型糖尿病");
        name.add("II型糖尿病");
        name.add("妊娠糖尿病");
        name.add("其他糖尿病");
        if (hashSet.size() > 0 && value.size() > 0) {
            for (String year : hashSet) {
                for (int i = 1; i <= 4; i++) {
                    if (!value.containsKey(year + "-I型糖尿病")) {
                        value.put(year + "-I型糖尿病", "0");
                    }
                    if (!value.containsKey(year + "-II型糖尿病")) {
                        value.put(year + "-II型糖尿病", "0");
                    }
                    if (!value.containsKey(year + "-妊娠糖尿病")) {
                        value.put(year + "-妊娠糖尿病", "0");
                    }
                    if (!value.containsKey(year + "-其他糖尿病")) {
                        value.put(year + "-其他糖尿病", "0");
                    }
                }
            }
            List<String> list1 = new ArrayList<>(); // I型糖尿病
            List<String> list2 = new ArrayList<>(); // II型糖尿病
            List<String> list3 = new ArrayList<>(); // 妊娠糖尿病
            List<String> list4 = new ArrayList<>(); // 其他糖尿病
            for (String year : hashSet) {
                for (String key : value.keySet()) {
                    if (key.equals(year + "-I型糖尿病")) {
                        list1.add(value.get(year + "-I型糖尿病"));
                    }
                    if (key.equals(year + "-II型糖尿病")) {
                        list2.add(value.get(year + "-II型糖尿病"));
                    }
                    if (key.equals(year + "-妊娠糖尿病")) {
                        list3.add(value.get(year + "-妊娠糖尿病"));
                    }
                    if (key.equals(year + "-其他糖尿病")) {
                        list4.add(value.get(year + "-其他糖尿病"));
                    }
                }
            }
            xData.clear();
            xData.addAll(hashSet);
            map.put("name", name);
            map.put("xName", xData);
            map.put("type1", list1);
            map.put("type2", list2);
            map.put("type3", list3);
            map.put("type4", list4);
        }
        return map;
    }
    /**
     * 性别分析
     * @param type
     * @param filter
     * @return
     */
    public Map<String, List<String>> getSexAnalysisInfo(String type, String filter) {
        String sql = "";
        if ("1".equals(type)) {
            sql = "select count(*) from singleDiseasePersonal group by sexName,date_histogram(field='eventDate','interval'='year')";
        } else {
            if(filter.isEmpty()){
                sql = "select count(*) from singleDiseasePersonal group by sexName,date_histogram(field='eventDate','interval'='month')";
            }else {
                sql = "select count(*) from singleDiseasePersonal where " + filter + "group by sexName,date_histogram(field='eventDate','interval'='month')";
            }
        }
        log.info("sql = " + sql);
        List<Map<String, Object>> listData = parseIntegerValue(sql);
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        Set<String> hashSet = new TreeSet<>();
        Map<String, String> value = new HashMap<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            if ("1".equals(type)) {
                listData.forEach(one -> {
                    hashSet.add((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4));
                    value.put((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4) + "-"+ one.get("sexName"), one.get("COUNT(*)") + "");
                });
            } else {
                hashSet.clear();
                hashSet.addAll(getMonthInfo());
                listData.forEach(one -> {
                    value.put((one.get("date_histogram(field=eventDate,interval=month)") + "").substring(5,7) + "-"+ one.get("sexName"), one.get("COUNT(*)") + "");
                });
            }
        }
        List<String> name = new ArrayList<>();
        name.add("女性");
        name.add("男性");
        name.add("未知");
        if (hashSet.size() > 0 && value.size() > 0) {
            for (String year : hashSet) {
                for (int i = 1; i <= 3; i++) {
                    if (!value.containsKey(year + "-女性")) {
                        value.put(year + "-女性", "0");
                    }
                    if (!value.containsKey(year + "-男性")) {
                        value.put(year + "-男性", "0");
                    }
                    if (!value.containsKey(year + "-未知")) {
                        value.put(year + "-未知", "0");
                    }
                }
            }
            List<String> list1 = new ArrayList<>(); // 女性
            List<String> list2 = new ArrayList<>(); // 男性
            List<String> list3 = new ArrayList<>(); // 未知
            for (String year : hashSet) {
                for (String key : value.keySet()) {
                    if (key.equals(year + "-女性")) {
                        list1.add(value.get(year + "-女性"));
                    }
                    if (key.equals(year + "-男性")) {
                        list2.add(value.get(year + "-男性"));
                    }
                    if (key.equals(year + "-未知")) {
                        list3.add(value.get(year + "-未知"));
                    }
                }
            }
            xData.clear();
            xData.addAll(hashSet);
            map.put("name", name);
            map.put("xName", xData);
            map.put("type1", list1);
            map.put("type2", list2);
            map.put("type3", list3);
        }
        return map;
    }
    /**
     * 年龄段分析
     * @param type
     * @param filter
     * @return
     */
    public Map<String, List<String>> getAgeAnalysisInfo(String type, String filter) {
        String sql = "";
        Calendar calendar = Calendar.getInstance();
        int years = calendar.get(Calendar.YEAR) + 1;
        /*
        * 年龄段分为0-6、7-17、18-40、41-65、65以上
        * 首先获取当前年份,由于ES查询是左包含,右不包,所以当前年份需要+1
        * 下面为构造年龄段的算式,其中year-151限定了范围是66-150岁 即66以上,其他类似
        * */
        String range = "range(birthYear," + (years - 151) + "," + (years - 66) + "," + (years - 41) + "," + (years - 18) + "," + (years - 7) + "," + years + ")";
        if ("1".equals(type)) {
            sql = "select count(birthYear) from singleDiseasePersonal group by " + range + ",date_histogram(field='eventDate','interval'='year')";
        } else {
            if(filter.isEmpty()){
                sql = "select count(birthYear) from singleDiseasePersonal group by " + range + ",date_histogram(field='eventDate','interval'='month')";
            }else {
                sql = "select count(birthYear) from singleDiseasePersonal where " + filter + " group by " + range + ",date_histogram(field='eventDate','interval'='month')";
            }
        }
        log.info("sql = " + sql);
        List<Map<String, Object>> listData = parseIntegerValue(sql);
        Map<String, List<String>> map = new HashMap<>();
        List<String> xData = new ArrayList<>();
        Set<String> hashSet = new TreeSet<>();
        Map<String, String> value = new HashMap<>();
        if (null != listData && listData.size() > 0 && listData.get(0).size() > 0) {
            if ("1".equals(type)) {
                listData.forEach(one -> {
                    String rangeName = one.get(range) + "";
                    // rangeName:"1978.0-2001.0"
                    int first = (int) Double.parseDouble(rangeName.split("-")[0]);
                    int last = (int) Double.parseDouble(rangeName.split("-")[1]);
                    Integer result = last - first;
                    // 转成相应的年龄段
                    String keyName = exchangeInfo(result);
                    hashSet.add((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4));
                    value.put((one.get("date_histogram(field=eventDate,interval=year)") + "").substring(0,4) + "-"+ keyName, one.get("COUNT(birthYear)") + "");
                });
            } else {
                hashSet.clear();
                hashSet.addAll(getMonthInfo());
                listData.forEach(one -> {
                    String rangeName = one.get(range) + "";
                    // rangeName:"1978.0-2001.0"
                    int first = (int) Double.parseDouble(rangeName.split("-")[0]);
                    int last = (int) Double.parseDouble(rangeName.split("-")[1]);
                    Integer result = last - first;
                    // 转成相应的年龄段
                    String keyName = exchangeInfo(result);
                    String strDate = one.get("date_histogram(field=eventDate,interval=month)") + "";
                    if(StringUtils.isNotEmpty(strDate) && strDate.length() > 7){
                        value.put(strDate.substring(5, 7) + "-"+ keyName, one.get("COUNT(birthYear)") + "");
                    }
                });
            }
        }
        List<String> name = new ArrayList<>();
        name.add("0-6岁");
        name.add("7-17岁");
        name.add("18-40岁");
        name.add("41-65岁");
        name.add("66岁以上");
        if (hashSet.size() > 0 && value.size() > 0) {
            for (String year : hashSet) {
                for (int i = 1; i <= 5; i++) {
                    if (!value.containsKey(year + "-0-6岁")) {
                        value.put(year + "-0-6岁", "0");
                    }
                    if (!value.containsKey(year + "-7-17岁")) {
                        value.put(year + "-7-17岁", "0");
                    }
                    if (!value.containsKey(year + "-18-40岁")) {
                        value.put(year + "-18-40岁", "0");
                    }
                    if (!value.containsKey(year + "-41-65岁")) {
                        value.put(year + "-41-65岁", "0");
                    }
                    if (!value.containsKey(year + "-66岁以上")) {
                        value.put(year + "-66岁以上", "0");
                    }
                }
            }
            List<String> list1 = new ArrayList<>(); // 0-6岁
            List<String> list2 = new ArrayList<>(); // 7-17岁
            List<String> list3 = new ArrayList<>(); // 18-40岁
            List<String> list4 = new ArrayList<>(); // 41-65岁
            List<String> list5 = new ArrayList<>(); // 66岁以上
            for (String year : hashSet) {
                for (String key : value.keySet()) {
                    if (key.equals(year + "-0-6岁")) {
                        list1.add(value.get(year + "-0-6岁"));
                    }
                    if (key.equals(year + "-7-17岁")) {
                        list2.add(value.get(year + "-7-17岁"));
                    }
                    if (key.equals(year + "-18-40岁")) {
                        list3.add(value.get(year + "-18-40岁"));
                    }
                    if (key.equals(year + "-41-65岁")) {
                        list4.add(value.get(year + "-41-65岁"));
                    }
                    if (key.equals(year + "-66岁以上")) {
                        list5.add(value.get(year + "-66岁以上"));
                    }
                }
            }
            xData.clear();
            xData.addAll(hashSet);
            map.put("name", name);
            map.put("xName", xData);
            map.put("type1", list1);
            map.put("type2", list2);
            map.put("type3", list3);
            map.put("type4", list4);
            map.put("type5", list5);
        }
        return map;
    }
    /**
     *
     * @param i
     * @param type 1糖尿病类型 2性别 3年龄
     * @return
     */
    public String getNameByIdType(int i, String type) {
        String result = "";
        if ("1".equals(type)) {
            switch (i) {
                case 1:
                    result = "I型糖尿病";
                    break;
                case 2:
                    result = "II型糖尿病";
                    break;
                case 3:
                    result = "妊娠糖尿病";
                    break;
                case 4:
                    result = "其他糖尿病";
                    break;
                default:
                    break;
            }
        } else if ("2".equals(type)) {
            switch (i) {
                case 1:
                    result = "女性";
                    break;
                case 2:
                    result = "男性";
                    break;
                case 3:
                    result = "未知";
                    break;
                default:
                    break;
            }
        } else if ("3".equals(type)) {
            switch (i) {
                case 1:
                    result = "0-6岁";
                    break;
                case 2:
                    result = "7-17岁";
                    break;
                case 3:
                    result = "18-40岁";
                    break;
                case 4:
                    result = "41-65岁";
                    break;
                case 5:
                    result = "66岁以上";
                    break;
                default:
                    break;
            }
        }
        return result;
    }
    public Set<String> getMonthInfo() {
        Set<String> hashSet = new TreeSet<>();
        hashSet.add("01");
        hashSet.add("02");
        hashSet.add("03");
        hashSet.add("04");
        hashSet.add("05");
        hashSet.add("06");
        hashSet.add("07");
        hashSet.add("08");
        hashSet.add("09");
        hashSet.add("10");
        hashSet.add("11");
        hashSet.add("12");
        return hashSet;
    }
}

+ 12 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDataSaveService.java

@ -2,11 +2,15 @@ package com.yihu.jw.basic.quota.service;
import com.yihu.jw.basic.quota.dao.XTjDataSaveRepository;
import com.yihu.jw.entity.ehr.quota.TjDataSave;
import com.yihu.jw.entity.ehr.quota.TjQuotaDataSave;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by Administrator on 2017/6/9.
 */
@ -25,4 +29,12 @@ public class TjDataSaveService extends BaseJpaService<TjDataSave, XTjDataSaveRep
        return tjDataSaveRepository.findByCode(code);
    }
    public TjQuotaDataSave findByQuota(String code) {
        String sql = "select   qds.*, ds.type from tj_data_save ds, tj_quota_data_save qds where ds.`code` = qds.save_code and qds.quota_code = ?";
        List<TjQuotaDataSave> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDataSave.class), code);
        if (quotaDataSources.size() > 0) {
            return quotaDataSources.get(0);
        }
        return null;
    }
}

+ 21 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDataSourceService.java

@ -3,11 +3,15 @@ package com.yihu.jw.basic.quota.service;
import com.yihu.jw.basic.quota.dao.XTjDataSourceRepository;
import com.yihu.jw.entity.ehr.quota.TjDataSource;
import com.yihu.jw.entity.ehr.quota.TjQuotaDataSource;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by Administrator on 2017/6/9.
 */
@ -25,4 +29,21 @@ public class TjDataSourceService extends BaseJpaService<TjDataSource, XTjDataSou
    public TjDataSource getByCode(String code) {
        return tjDataSourceRepository.findByCode(code);
    }
    public TjQuotaDataSource findSourceByQuotaCode(String code) {
        String sql = " SELECT " +
                "  qds.*, ds.code " +
                "FROM " +
                "  tj_quota_data_source qds, " +
                "  tj_data_source ds " +
                "WHERE " +
                "  qds.source_code = ds.`code` " +
                "  and " +
                "  qds.quota_code = ?";
        List<TjQuotaDataSource> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDataSource.class), code);
        if (quotaDataSources.size() > 0) {
            return quotaDataSources.get(0);
        }
        return null;
    }
}

+ 11 - 2
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDimensionMainService.java

@ -3,9 +3,11 @@ package com.yihu.jw.basic.quota.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.quota.dao.XTjDimensionMainRepository;
import com.yihu.jw.entity.ehr.quota.TjDimensionMain;
import com.yihu.jw.entity.ehr.quota.TjQuotaDimensionMain;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -31,8 +33,8 @@ public class TjDimensionMainService extends BaseJpaService<TjDimensionMain, XTjD
     * 根据ID获取.
     * @param
     */
    public TjDimensionMain getTjDimensionMain(Integer id) {
        TjDimensionMain tjDimensionMain = tjDimensionMainRepository.getOne(Long.valueOf(id));
    public TjDimensionMain getTjDimensionMain(Long id) {
        TjDimensionMain tjDimensionMain = tjDimensionMainRepository.getOne(id);
        return tjDimensionMain;
    }
@ -55,4 +57,11 @@ public class TjDimensionMainService extends BaseJpaService<TjDimensionMain, XTjD
        sqlQuery.setParameterList("values", values);
        return sqlQuery.list();
    }
    public List<TjQuotaDimensionMain> findTjQuotaDimensionMainByQuotaCode(String code) {
        String sql = "SELECT  qdm.*, dm.type FROM   tj_dimension_main dm, tj_quota_dimension_main qdm " +
                "WHERE   dm.`code` = qdm.main_code AND qdm.quota_code = ? order by qdm.id asc";
        List<TjQuotaDimensionMain> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDimensionMain.class), code);
        return quotaDataSources;
    }
}

+ 16 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/quota/service/TjDimensionSlaveService.java

@ -2,9 +2,11 @@ package com.yihu.jw.basic.quota.service;
import com.yihu.jw.basic.quota.dao.XTjDimensionSlaveRepository;
import com.yihu.jw.entity.ehr.quota.TjDimensionSlave;
import com.yihu.jw.entity.ehr.quota.TjQuotaDimensionSlave;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -50,4 +52,18 @@ public class TjDimensionSlaveService extends BaseJpaService<TjDimensionSlave, XT
        sqlQuery.setParameterList("values", values);
        return sqlQuery.list();
    }
    public List<TjQuotaDimensionSlave> findTjQuotaDimensionSlaveByQuotaCode(String code) {
        String sql = "SELECT " +
                "  qdm.*,dm.type " +
                " FROM " +
                "  tj_dimension_slave dm, " +
                "  tj_quota_dimension_slave qdm " +
                " WHERE " +
                "  dm.`code` = qdm.slave_code " +
                " AND qdm.quota_code = ? order BY" +
                " qdm.id asc ";
        List<TjQuotaDimensionSlave> quotaDataSources = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TjQuotaDimensionSlave.class), code);
        return quotaDataSources;
    }
}

+ 0 - 2
svr/svr-basic/src/main/java/com/yihu/jw/basic/report/controller/QcQuotaResultEndPoint.java

@ -35,8 +35,6 @@ import java.util.*;
@Api(value = "QcQuotaResult", description = "数据统计指标结果", tags = {"数据统计指标结果"})
public class QcQuotaResultEndPoint extends EnvelopRestEndpoint {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    QcQuotaResultService qcQuotaResultService;
    CalculatePointUtil calculatePointUtil=new CalculatePointUtil();

+ 19 - 6
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/controller/RsResourceGrantEndPoint.java

@ -2,6 +2,7 @@ package com.yihu.jw.basic.resource.controller;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.basic.resource.dao.*;
import com.yihu.jw.entity.ehr.resource.RsAppResourceMetadata;
import com.yihu.jw.restmodel.ehr.org.MRsOrgResource;
@ -46,16 +47,28 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private RsResourceGrantService rsGrantService;
    @Autowired
    private RsAppResourceDao appRsDao;
    @Autowired
    private RsAppResourceMetadataGrantService rsMetadataGrantService;
    @Autowired
    private RsAppResourceMetadataDao appRsMetadataDao;
    @Autowired
    private RsRolesResourceMetadataGrantService rolesResourceMetadataGrantService;
    @Autowired
    private RsRolesResourceMetadataDao rsRolesResourceMetadataDao;
    @Autowired
    private RsRolesResourceGrantService rolesResourceGrantService;
    @Autowired
    private RsRolesResourceDao rsRolesResourceDao;
    @Autowired
    private RsOrgResourceGrantService orgResourceGrantService;
    @Autowired
    private RsOrgResourceDao orgRsDao;
    @Autowired
    private RsOrgResourceMetadataGrantService orgResourceMetadataGrantService;
    @Autowired
    private RsOrgResourceMetadataDao OrgResourceMetadataDao;
    @Autowired
    private RsResourceMetadataService rsResourceMetadataService;
    @ApiOperation("单个应用授权多个资源")
@ -286,7 +299,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
    public Collection<MRsAppResourceMetadata> getAppRsMetadatas(
            @ApiParam(name = "app_res_id", value = "授权应用编号", defaultValue = "1")
            @PathVariable(value = "app_res_id") String appResId) throws Exception {
        RsAppResource appResource = rsGrantService.retrieve(appResId);
        RsAppResource appResource = appRsDao.getOne(appResId);
        List<RsAppResourceMetadata> rsMetadataGrant = new ArrayList<>();
        if (appResource != null) {
            rsMetadataGrant = rsMetadataGrantService.getAppRsMetadatas(appResource.getId(), appResource.getAppId(), appResource.getResourceId());
@ -332,7 +345,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
            @ApiParam(name = "dimension", value = "授权ID", defaultValue = "")
            @RequestParam(value = "dimension") String dimension) throws Exception {
        RsAppResourceMetadata rsAppResourceMetadata = rsMetadataGrantService.retrieve(id);
        RsAppResourceMetadata rsAppResourceMetadata = appRsMetadataDao.getOne(id);
        rsAppResourceMetadata.setDimensionValue(dimension);
        rsMetadataGrantService.save(rsAppResourceMetadata);
        return convertToModel(rsAppResourceMetadata, MRsAppResourceMetadata.class);
@ -430,7 +443,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
            @ApiParam(name = "dimension", value = "授权ID", defaultValue = "")
            @RequestParam(value = "dimension") String dimension) throws Exception {
        RsRolesResourceMetadata rsRolesResourceMetadata = rolesResourceMetadataGrantService.retrieve(id);
        RsRolesResourceMetadata rsRolesResourceMetadata = rsRolesResourceMetadataDao.getOne(id);
        rsRolesResourceMetadata.setDimensionValue(dimension);
        rolesResourceMetadataGrantService.save(rsRolesResourceMetadata);
        return convertToModel(rsRolesResourceMetadata, MRsRolesResourceMetadata.class);
@ -498,7 +511,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
            @PathVariable(value = "roles_res_id") String rolesResId,
            @ApiParam(name = "appId", value = "应用编号", defaultValue = "")
            @RequestParam(value = "appId", required = false) String appId) throws Exception {
        RsRolesResource rolesResource = rolesResourceGrantService.retrieve(rolesResId);
        RsRolesResource rolesResource = rsRolesResourceDao.getOne(rolesResId);
        List<RsRolesResourceMetadata> rsMetadataGrant = new ArrayList<>();
        List<RsRolesResourceMetadata> rsMetadataGrantApp = new ArrayList<>();
        if (rolesResource != null) {
@ -618,7 +631,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
            @ApiParam(name = "dimension", value = "授权ID", defaultValue = "")
            @RequestParam(value = "dimension") String dimension) throws Exception {
        RsOrgResourceMetadata rsOrgResourceMetadata = orgResourceMetadataGrantService.retrieve(id);
        RsOrgResourceMetadata rsOrgResourceMetadata = OrgResourceMetadataDao.getOne(id);
        rsOrgResourceMetadata.setDimensionValue(dimension);
        orgResourceMetadataGrantService.save(rsOrgResourceMetadata);
        return convertToModel(rsOrgResourceMetadata, MRsOrgResourceMetadata.class);
@ -662,7 +675,7 @@ public class RsResourceGrantEndPoint extends EnvelopRestEndpoint {
    public Collection<MRsOrgResourceMetadata> getOrgRsMetadatas(
            @ApiParam(name = "Org_res_id", value = "授权应用编号", defaultValue = "1")
            @PathVariable(value = "Org_res_id") String orgResId) throws Exception {
        RsOrgResource orgResource = orgResourceGrantService.retrieve(orgResId);
        RsOrgResource orgResource = orgRsDao.getOne(orgResId);
        List<RsOrgResourceMetadata> rsMetadataGrant = new ArrayList<>();
        if (orgResource != null) {
            rsMetadataGrant = orgResourceMetadataGrantService.getOrgRsMetadatas(orgResource.getId(), orgResource.getOrganizationId(), orgResource.getResourceId());

+ 1 - 5
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/RsResourceDefaultParamDao.java

@ -11,7 +11,7 @@ import java.util.List;
 * @author linaz
 * @created 2016.05.17 16:33
 */
public interface RsResourceDefaultParamDao extends JpaRepository<RsResourceDefaultParam, Long> {
public interface RsResourceDefaultParamDao extends JpaRepository<RsResourceDefaultParam, String> {
    List<RsResourceDefaultParam> findByResourcesCode(String resourcesCode);
@ -24,8 +24,4 @@ public interface RsResourceDefaultParamDao extends JpaRepository<RsResourceDefau
    @Query("from RsResourceDefaultParam where ( resourcesId = ?1 or resourcesCode = ?2 ) and paramKey = ?3 ")
    List<RsResourceDefaultParam> findByResourcesIdOrResourcesCodeWithParamKey(String resourceId, String resourceCode , String ParamKey);
    @Query("select rdf from RsResourceDefaultParam rdf where rdf.id = :id")
    RsResourceDefaultParam findById(@Param("id") String id);
}

+ 7 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/RsResourceQuotaDao.java

@ -17,6 +17,9 @@ public interface RsResourceQuotaDao extends JpaRepository<RsResourceQuota,Intege
    @Modifying
    int deleteByResourceId(@Param("resourceId") String resourceId);
    @Query("select count(rq.quotaId) from RsResourceQuota rq where rq.resourceId = :resourceId")
    Integer fingQuotaCount(@Param("resourceId") String resourceId);
    @Query("select rq.quotaChart from RsResourceQuota rq where rq.quotaId = :quotaId and rq.resourceId = :resourceId")
    List<Integer> findQuotaChartByQuotaId(@Param("quotaId")Integer quotaId, @Param("resourceId") String resourceId);
@ -32,5 +35,9 @@ public interface RsResourceQuotaDao extends JpaRepository<RsResourceQuota,Intege
    @Query("select  rq FROM RsResourceQuota rq WHERE rq.resourceId = :resourceId and rq.quotaId = :quotaId")
    RsResourceQuota findByResourceIdAndQuotaId(@Param("resourceId")String resourceId, @Param("quotaId")Integer quotaId);
    @Query("select rq from RsResourceQuota rq where rq.resourceId = :resourceId and rq.pid in (:pid)")
    List<RsResourceQuota> findChildByPidAndResourceIds(@Param("resourceId") String resourceId, @Param("pid") List<Integer> pid);
    List<RsResourceQuota> findByResourceId(String resourceId);
}

+ 4 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsInterfaceService.java

@ -27,4 +27,8 @@ public class RsInterfaceService extends BaseJpaService<RsInterface, RsInterfaceD
        return list == null?null:list.get(0);
    }
    public RsInterface getOne(String id){
       return rsInterfaceDao.getOne(id);
    }
}

+ 1 - 1
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsResourceDefaultParamService.java

@ -21,7 +21,7 @@ public class RsResourceDefaultParamService extends BaseJpaService<RsResourceDefa
    private RsResourceDefaultParamDao resourceDefaultParamDao;
    public RsResourceDefaultParam findById(String id) {
        return resourceDefaultParamDao.findById(id);
        return resourceDefaultParamDao.getOne(id);
    }
    public List<RsResourceDefaultParam> findByResourcesIdOrResourcesCodeWithParamKey(String resourcesId, String resourcesCode, String paramKey){

+ 15 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/RsResourceQuotaService.java

@ -24,6 +24,21 @@ public class RsResourceQuotaService extends BaseJpaService<RsResourceQuota, RsRe
    @Autowired
    private RsResourceQuotaDao resourceQuotaDao;
    public Integer getQuotaCount(String resourceId) {
        Integer count = resourceQuotaDao.fingQuotaCount(resourceId);
        return count;
    }
    public List<RsResourceQuota> getChildrenByPidList(List<Integer> pid, String resourceId) {
        List<RsResourceQuota> children = new ArrayList<>();
        if (null == pid || pid.size() == 0) {
            children = resourceQuotaDao.getTopParents(resourceId);
        } else {
            children = resourceQuotaDao.findChildByPidAndResourceIds(resourceId, pid);
        }
        return children;
    }
    public void deleteByResourceId(String resourceId) {
        resourceQuotaDao.deleteByResourceId(resourceId);
    }

+ 72 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/util/BasesicUtil.java

@ -0,0 +1,72 @@
package com.yihu.jw.basic.util;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by janseny on 2017/12/14.
 */
public class BasesicUtil {
    /**
     * 根据属性名获取属性值
     * */
    public String getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value.toString();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * date1 大 返回 1
     * date2 大 返回-1
     * 相等 返回 0
     * @param DATE1
     * @param DATE2
     * @return
     */
    public int compareDate(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }
    /**
     * 保留2位小数,如果有小数则保留2位小数
     * @param data
     * @return
     */
    public String decimalPointHandle(Object data) {
        DecimalFormat df = new DecimalFormat("#0.00");
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumFractionDigits(2);
        String format = nf.format(data);
        if (format.indexOf(".") != -1) {
            format = df.format(Double.parseDouble(format));
        }
        return format;
    }
}

+ 387 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/util/ReportOption.java

@ -0,0 +1,387 @@
package com.yihu.jw.basic.util;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Polar;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.*;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.data.PieData;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.series.Radar;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;
import com.yihu.jw.basic.util.model.ChartDataModel;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2017/8/9.
 */
public class ReportOption {
    public static int bar = 1;
    public static int line = 2;
    public static int pie = 3;
    public static int radar = 4;
    /**
     * 折线图和柱状  都支持
     * @param title  标题
     * @param xName x轴名称
     * @param yName yz轴名称
     * @param xData x轴数据集
     * @param lineDatas 数据集
     * @param lineNames 折线名称集合
     */
    public Option getLineEchartOptionMoreChart(String title, String xName, String yName, Object[] xData,  List<List<Object>> lineDatas, List<String> lineNames,List<String> types) {
        Option option = new GsonOption();
        //title
        option.title().setText(title);
//        option.title().setSubtext(title);//小标题
        option.title().x("center");
        //tooltip
        option.tooltip().trigger(Trigger.axis);
        //toolbox
        //grid
        option.grid().x("50px");  // left
        option.grid().y("40px");  // top
        option.grid().x2("80px"); // right
        option.grid().y2("50px"); // bottom
//        option.grid().containLabel(true);
        //yAxis
        ValueAxis valueAxis = new ValueAxis();
        valueAxis.name(yName);
        valueAxis.type(AxisType.value);
//        valueAxis.axisLabel().formatter("℃");//单位
        option.yAxis(valueAxis);
        //xAxis
        CategoryAxis categoryAxis = new CategoryAxis();
        categoryAxis.name(xName);
        categoryAxis.type(AxisType.category);
//        AxisTick axisTick = new AxisTick();
//        axisTick.setType
//        categoryAxis.axisTick(axisTick);
        categoryAxis.data(xData);
        option.xAxis(categoryAxis);
        if(lineNames.size() > 0 && lineDatas.size() >0 && lineNames.size() == lineDatas.size()) {
            for (int i = 0; i < lineDatas.size(); i++) {
                String lineName = lineNames.get(i);
                String type = "";
                if (types.size() > i) {
                    type = types.get(i);
                } else {
                    type = types.get(types.size() > 0 ? types.size() -1 : 0);
                }
                //series
                Line line = new Line();
                line.name(lineName);
                if (type.equals(String.valueOf(ReportOption.bar))) {
                    line.type(SeriesType.bar);
                } else if (type.equals(String.valueOf(ReportOption.line))) {
                    line.type(SeriesType.line);
                }
                line.smooth(true);
//                line.stack("stack");
                line.itemStyle().normal().lineStyle().shadowColor("rgba(0,0,0,0.4)");
                line.itemStyle().normal().label().show(true);   // 设置在图形中显示出具体的数值
                line.itemStyle().normal().label().position(Position.top);   // 设置显示数值的位置
                List<Object> lineValList = lineDatas.get(i);
                Object[] lineVal = (Object[]) lineValList.toArray(new Object[lineValList.size()]);
                line.data(lineVal);
                option.series().add(line);
            }
        }
        return option;
    }
    /**
     * 饼状图
     * @param title 标题
     * @param legend 副标题
     * @param datalist 数据集1
     * @param data2list 数据集2
     */
    public Option getPieEchartOption(String title,String legend ,String pieName,List<Map<String, Object>> datalist ,
                                     String pie2Name,List<Map<String, Object>> data2list) {
        Option option = new GsonOption();
        //title
        option.title().setText(title);
        option.title().setSubtext(title);
        option.title().x("center");
        //tooltip
        option.tooltip().trigger(Trigger.item);
//        option.tooltip().formatter("{a} <br/>{b} : {c} ({d}%)");
        //toolbox
//        option.toolbox().show(false);
//        DataView dataView = new DataView();
//        dataView.show(true);
//        dataView.readOnly(false);
//        option.toolbox().feature().put("dataView", Feature.dataView);
//        MagicType magicType = new MagicType();
//        magicType.show(true);
//        List<String> typeList = new ArrayList<String>();
//        typeList.add("pie");
//        typeList.add("funnel");
//        magicType.setType(typeList);
//        option.toolbox().feature().put("magicType", magicType);
//        Restore restore = new Restore();
//        restore.show(true);
//        option.toolbox().feature().put("restore", restore);
//        SaveAsImage saveAsImage = new SaveAsImage();
//        saveAsImage.show(true);
//        option.toolbox().feature().put("saveAsImage", saveAsImage);
//
//        //legend (数据需填充)
//        option.legend().orient(Orient.vertical);
//        option.legend().left(X.left);
//        List<String> legendDataList = new ArrayList<String>();
//        legendDataList.add(legend);
//        option.legend().data(legendDataList);
        //series
        Pie pie = new Pie();
        pie.name(pieName);
        pie.type(SeriesType.pie);
        pie.radius("40%");
        if (null != data2list && data2list.size() > 0) {
            pie.center(new String[]{"25%", "50%"});
        } else {
            pie.center(new String[]{"50%", "50%"});
        }
        pie.itemStyle().normal().labelLine().show(false);
        pie.itemStyle().normal().label().show(false);
//        pie.itemStyle().emphasis().shadowBlur(10);
//        pie.itemStyle().emphasis().shadowOffsetX(0);
//        pie.itemStyle().emphasis().shadowColor("rgba(0, 0, 0, 0.5)");
        List<Object> lineNameList = getList(datalist,"NAME");
        List<Object> lineValList = getList(datalist,"TOTAL");
        List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
        for(int i =0 ;i < lineValList.size() ; i++){
            if (StringUtils.isNotEmpty(lineValList.get(i) + "") && Double.parseDouble(lineValList.get(i) + "") != 0) {
                Map<String,Object> map = new HashMap<>();
                map.put("value",lineValList.get(i));
                map.put("name",lineNameList.get(i));
                dataList.add(map);
            }
        }
        List<Object> list = new ArrayList<>(dataList);
        pie.setData(list);
        option.series().add(pie);
        if(data2list != null && data2list.size() > 0){
            Pie pie2 = new Pie();
            pie2.name(pie2Name);
            pie2.type(SeriesType.pie);
            pie2.radius("40%");
            pie2.center(new String[]{"70%", "50%"});
//            pie2.itemStyle().emphasis().shadowBlur(10);
//            pie2.itemStyle().emphasis().shadowOffsetX(0);
//            pie2.itemStyle().emphasis().shadowColor("rgba(0, 0, 0, 0.5)");
            List<Object> lineNameList2 = getList(data2list,"NAME");
            List<Object> lineValList2 = getList(data2list,"TOTAL");
            List<Map<String,Object>> dataList2 = new ArrayList<Map<String,Object>>();
            for(int i =0 ;i < lineValList2.size() ; i++){
                if (StringUtils.isNotEmpty(lineValList2.get(i) + "") && Double.parseDouble(lineValList2.get(i) + "") != 0) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("value",lineValList2.get(i));
                    map.put("name",lineNameList2.get(i));
                    dataList2.add(map);
                }
            }
            List<Object> list2 = new ArrayList<>(dataList2);
            pie2.setData(list2);
            option.series().add(pie2);
        }
        return option;
    }
    /**
     * 柱状+饼状 图
     */
    public Option getBarPieEchartOption(String title,String legend ,List<Map<String, Object>> Datalist) {
        List<Map<String, Object>> list = new ArrayList<>();
        //创建Option
        Option option = new Option();
        option.title("剔除药品").tooltip(Trigger.axis).legend("金额(元)");
        //横轴为值轴
        option.xAxis(new ValueAxis().boundaryGap(0d, 0.01));
        //创建类目轴
        CategoryAxis category = new CategoryAxis();
        //柱状数据
        Bar bar = new Bar("金额(元)");
        //饼图数据
        Pie pie = new Pie("金额(元)");
        //循环数据
        for (Map<String, Object> objectMap : list) {
            //设置类目
            category.data(objectMap.get("NAME"));
            //类目对应的柱状图
            bar.data(objectMap.get("TOTAL"));
            //饼图数据
            pie.data(new PieData(objectMap.get("NAME").toString(), objectMap.get("TOTAL")));
        }
        //设置类目轴
        option.yAxis(category);
        //饼图的圆心和半径
        pie.center(900,380).radius(100);
        //设置数据
        option.series(bar, pie);
        //由于药品名字过长,图表距离左侧距离设置180,关于grid可以看ECharts的官方文档
        option.grid().x(180);
        return option;
    }
    public List<Object> getList(List<Map<String, Object>> dataList,String keyName){
        List<Object> returnList = new ArrayList<>();
        if(dataList != null){
            for (Map<String, Object> objectMap : dataList) {
                for(String key:objectMap.keySet()){
                    returnList.add(objectMap.get(keyName));
                    break;
                }
            }
        }
        return  returnList;
    }
    /**
     *雷达图
     *
     * @param title
     * @param dataList
     * @param count 图形边框最大值
     * @return
     */
    public Option getRadarEchartOption(String title, List<Map<String, Object>> dataList, Integer count) {
        Option option = new GsonOption();
        option.title().setText(title);
        option.tooltip().trigger(Trigger.axis);
        option.tooltip().axisPointer().type(PointerType.shadow);
//        option.grid().left("3%");
//        option.grid().right("9%");
//        option.grid().top("22%");
//        option.grid().bottom("3%");
//        option.grid().containLabel(true);
        // radar 极坐标
        Polar polar = new Polar();
        List<Object> radarNameList = new ArrayList<>();
        Object[] radarVal = new Integer[dataList.size()];   // 数据
        for (int i = 0; i < dataList.size(); i++) {
            for(Map.Entry<String, Object> vo : dataList.get(i).entrySet()) {
                polar.indicator(new Data().text(vo.getKey()).max(count));
                radarNameList.add(vo.getKey());
                radarVal[i] = vo.getValue();
            }
        }
        option.polar(polar);
        // series
        Radar radar = new Radar();
        radar.data(new Data().name(title).value(radarVal));
        radar.itemStyle().normal().areaStyle().type("default");
        option.series().add(radar);
        return option;
    }
    /**
     * 嵌套饼图
     *
     * @param title
     * @param dataModel
     * @return
     */
    public Option getNestedPieEchartOption(String title, ChartDataModel dataModel) {
        Option option = new GsonOption();
        // title
        option.title().setText(title);
//        option.title().setSubtext(title);
//        option.title().x("center");
        // tooltip
        option.tooltip().trigger(Trigger.item);
        // series
        List<Pie> pieList = new ArrayList<>();
        pieList = getPie(pieList, dataModel);
        String temp = "20";
        for (int i = 0; i < pieList.size(); i++) {
            Pie pie = pieList.get(i);
            pie.name(title);
            if (i == 0) {
                pie.radius("5%", "20%");
            } else {
                pie.radius((Integer.parseInt(temp) + 5) + "%", (Integer.parseInt(temp) + 20 )+ "%");
                temp = (Integer.parseInt(temp) + 20) + "";
            }
            option.series().add(pie);
        }
        return option;
    }
    public List<Pie> getPie(List<Pie> pieList, ChartDataModel dataModel) {
        Pie pie = new Pie();
        if (null == dataModel.getChildren()) {
            pie = envelopPie(pie, dataModel.getList());
            pieList.add(pie);
            return pieList;
        } else {
            pie = envelopPie(pie, dataModel.getList());
            pieList.add(pie);
            pieList = getPie(pieList, dataModel.getChildren());
            return pieList;
        }
    }
    public Pie envelopPie(Pie pie, List<Map<String, Object>> dataModel) {
        pie.type(SeriesType.pie);
        Normal normal = new Normal();
        normal.label().position("inner");
        normal.labelLine().show(false);
        ItemStyle itemStyle = new ItemStyle();
        itemStyle.normal(normal);
        pie.setItemStyle(itemStyle);
//        pie.label().normal(normal);
//        pie.itemStyle().emphasis().shadowBlur(10);
//        pie.itemStyle().emphasis().shadowOffsetX(0);
//        pie.itemStyle().emphasis().shadowColor("rgba(0, 0, 0, 0.5)");
        List<Object> pieNameList = getList(dataModel,"NAME");
        List<Object> pieValList = getList(dataModel,"TOTAL");
        List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
        for(int i = 0 ;i < pieValList.size(); i++){
            Map<String,Object> map = new HashMap<>();
            map.put("value", pieValList.get(i));
            map.put("name", pieNameList.get(i));
            dataList.add(map);
        }
//        pie.setData(dataList);
        List<Object> list = new ArrayList<>(dataList);
        pie.setData(list);
        return pie;
    }
}

+ 29 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/util/model/ChartDataModel.java

@ -0,0 +1,29 @@
package com.yihu.jw.basic.util.model;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/12/12.
 */
public class ChartDataModel implements Serializable {
    private List<Map<String, Object>> list;
    private ChartDataModel children;
    public List<Map<String, Object>> getList() {
        return list;
    }
    public void setList(List<Map<String, Object>> list) {
        this.list = list;
    }
    public ChartDataModel getChildren() {
        return children;
    }
    public void setChildren(ChartDataModel children) {
        this.children = children;
    }
}

+ 3 - 1
svr/svr-basic/src/main/resources/application.yml

@ -33,7 +33,9 @@ spring:
        max-idle: 8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
        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.
  jackson:
    serialization:
      fail-on-empty-beans: false
fast-dfs:
  connect-timeout: 10
  network-timeout: 60