Browse Source

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

zd_123 7 years ago
parent
commit
f1d8d505eb
45 changed files with 3027 additions and 1231 deletions
  1. 118 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/charge/WlyyCharge.java
  2. 10 1
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prenatal/PrenatalInspectorPlan.java
  3. 47 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionPay.java
  4. 159 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/zydict/ZyZoneDict.java
  5. 15 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/PrescriptionController.java
  6. 23 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java
  7. 12 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/SignZYService.java
  8. 19 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java
  9. 33 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java
  10. 17 1
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java
  11. 55 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/OnePayQueryJob.java
  12. 36 30
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PrenatalInspectorJob.java
  13. 57 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PrescriptionPayQueryJob.java
  14. 5 1
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/charge/ChargeDao.java
  15. 20 20
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanDao.java
  16. 20 20
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanLibraryDao.java
  17. 17 17
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPreCardDao.java
  18. 8 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionPayDao.java
  19. 12 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/ylz/PayLogDao.java
  20. 251 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/charge/OnePayService.java
  21. 85 240
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java
  22. 304 37
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prescription/PatientPrescriptionPayService.java
  23. 58 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/third/ylz/PayLogService.java
  24. 0 129
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java
  25. 17 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/quota/JobController.java
  26. 3 0
      patient-co/patient-co-wlyy-job/src/main/resources/system.properties
  27. 1 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/adapter/PresModeAdapter.java
  28. 10 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanDao.java
  29. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanLibraryDao.java
  30. 11 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/zydict/ZyZoneDictDao.java
  31. 179 117
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java
  32. 266 210
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PatientPrescriptionPayService.java
  33. 72 8
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsService.java
  34. 575 66
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java
  35. 2 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java
  36. 11 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/jw/JwMaternalChildService.java
  37. 19 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/jw/ZyDictService.java
  38. 0 129
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java
  39. 191 64
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/weixin/wxpay/service/OnePayService.java
  40. 14 7
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java
  41. 8 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/prenatalInspector/PrenatalInspectorContoller.java
  42. 6 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/prescription/PatientPrescriptionPayController.java
  43. 32 16
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java
  44. 226 103
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/wx/OnePayController.java
  45. 2 2
      patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu.txt

+ 118 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/charge/WlyyCharge.java

@ -22,6 +22,7 @@ public class WlyyCharge extends IdEntity {
	private String patient;   //  用户
	private String openid;   //  用戶微信openid
	private String ssc;   // 医保卡号
	private String principalSsc;   // 实际签约卡号
	private String name;   //  姓名
	private String idType;   //  证件类型
	private String idNo;   //  证件号码
@ -45,6 +46,123 @@ public class WlyyCharge extends IdEntity {
	private String billNo;   //  待结算费用单据号
	private Date updateTime;//修改时间
	private String miCollectDate;//收费日期
	private String miCollectTime;//收费时间
	private String miSettleNo;//医保收费单据号 (医保签约号)
	private String miCollectStatus;//扣费状态
	private String miRegisterStatus;//登记状态
	private String cadresPay;//公务员补助
	private String miTotalFee;//本次报销总额
	private String healthCarePay;//保健基金支付
	private String heathPay;//健康账户支付
	private String accountPay;//个人账户支付
	private String selfPay;//个人现金支付
	private String civilPay;//民政补助金额
	public String getPrincipalSsc() {
		return principalSsc;
	}
	public void setPrincipalSsc(String principalSsc) {
		this.principalSsc = principalSsc;
	}
	public String getMiCollectDate() {
		return miCollectDate;
	}
	public void setMiCollectDate(String miCollectDate) {
		this.miCollectDate = miCollectDate;
	}
	public String getMiCollectTime() {
		return miCollectTime;
	}
	public void setMiCollectTime(String miCollectTime) {
		this.miCollectTime = miCollectTime;
	}
	public String getMiSettleNo() {
		return miSettleNo;
	}
	public void setMiSettleNo(String miSettleNo) {
		this.miSettleNo = miSettleNo;
	}
	public String getMiCollectStatus() {
		return miCollectStatus;
	}
	public void setMiCollectStatus(String miCollectStatus) {
		this.miCollectStatus = miCollectStatus;
	}
	public String getMiRegisterStatus() {
		return miRegisterStatus;
	}
	public void setMiRegisterStatus(String miRegisterStatus) {
		this.miRegisterStatus = miRegisterStatus;
	}
	public String getCadresPay() {
		return cadresPay;
	}
	public void setCadresPay(String cadresPay) {
		this.cadresPay = cadresPay;
	}
	public String getMiTotalFee() {
		return miTotalFee;
	}
	public void setMiTotalFee(String miTotalFee) {
		this.miTotalFee = miTotalFee;
	}
	public String getHealthCarePay() {
		return healthCarePay;
	}
	public void setHealthCarePay(String healthCarePay) {
		this.healthCarePay = healthCarePay;
	}
	public String getHeathPay() {
		return heathPay;
	}
	public void setHeathPay(String heathPay) {
		this.heathPay = heathPay;
	}
	public String getAccountPay() {
		return accountPay;
	}
	public void setAccountPay(String accountPay) {
		this.accountPay = accountPay;
	}
	public String getSelfPay() {
		return selfPay;
	}
	public void setSelfPay(String selfPay) {
		this.selfPay = selfPay;
	}
	public String getCivilPay() {
		return civilPay;
	}
	public void setCivilPay(String civilPay) {
		this.civilPay = civilPay;
	}
	public String getChargeType() {
		return chargeType;
	}

+ 10 - 1
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prenatal/PrenatalInspectorPlan.java

@ -17,7 +17,7 @@ import java.util.Date;
@Table(name = "wlyy_prenatal_inspector_plan")
public class PrenatalInspectorPlan extends IdEntity implements Serializable {
    private String inspectionCode;//产检code
    private String inspectionCode;//产检code,有建卡记录才有值
    private String patient;//居民code
    private String name;//名称
    private Date inspectionTime;//产检时间
@ -29,6 +29,7 @@ public class PrenatalInspectorPlan extends IdEntity implements Serializable {
    private String status;//产检状态(0未产检,1已产检)
    private String inspectionPhase;//检查阶段(1社区检查,2医院检查)
    private String signHospital;//签约医院code(已签约且社区检查阶段才有值)
    private String del;//1: 正常 0: 删除
    private Date czrq;//创建日期
    public String getInspectionCode() {
@ -142,4 +143,12 @@ public class PrenatalInspectorPlan extends IdEntity implements Serializable {
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
}

+ 47 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionPay.java

@ -58,6 +58,53 @@ public class PrescriptionPay extends IdEntity {
    private String mxlist;//处方明细
    private Date createTime;//续方确认支付时间
    private Date czrq;//续方记录最后操作时间
    //    易联众新增查询返回字段v1.3.7
    private String medOrgNo;//医疗机构编号
    private String medOrgName;//医疗机构名称
    private Date traceTime;//交易成功时间
    private String traceNo;//支付平台跟踪号
    private String principalCardNo;//实际签约卡号
    public String getPrincipalCardNo() {
        return principalCardNo;
    }
    public void setPrincipalCardNo(String principalCardNo) {
        this.principalCardNo = principalCardNo;
    }
    public Date getTraceTime() {
        return traceTime;
    }
    public void setTraceTime(Date traceTime) {
        this.traceTime = traceTime;
    }
    public String getTraceNo() {
        return traceNo;
    }
    public void setTraceNo(String traceNo) {
        this.traceNo = traceNo;
    }
    public String getMedOrgNo() {
        return medOrgNo;
    }
    public void setMedOrgNo(String medOrgNo) {
        this.medOrgNo = medOrgNo;
    }
    public String getMedOrgName() {
        return medOrgName;
    }
    public void setMedOrgName(String medOrgName) {
        this.medOrgName = medOrgName;
    }
    public Integer getAccountBalance() {
        return accountBalance;

+ 159 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/zydict/ZyZoneDict.java

@ -0,0 +1,159 @@
package com.yihu.wlyy.entity.zydict;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 智业地区字典
 * Created by yeshijie on 2017/10/10.
 */
@Entity
@Table(name = "zy_zone_dict")
public class ZyZoneDict extends IdEntity{
    private String orgId;//ORG_ID
    private String zoneCode;//地区编码
    private String zoneName;//名称
    private String zoneLevel;//级别
    private String validFlag;//有效标志
    private String userCode;//用户code
    private String customCode;//
    private String spellCode;//
    private String wbzxCode;//
    private String sortNo;//
    private String createTime;//
    private String createOperator;//
    private String modifyTime;//
    private String modifyOperator;//
    private String remark;//
    private String healthArchiveNo;//
    public String getOrgId() {
        return orgId;
    }
    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }
    public String getZoneCode() {
        return zoneCode;
    }
    public void setZoneCode(String zoneCode) {
        this.zoneCode = zoneCode;
    }
    public String getZoneName() {
        return zoneName;
    }
    public void setZoneName(String zoneName) {
        this.zoneName = zoneName;
    }
    public String getZoneLevel() {
        return zoneLevel;
    }
    public void setZoneLevel(String zoneLevel) {
        this.zoneLevel = zoneLevel;
    }
    public String getValidFlag() {
        return validFlag;
    }
    public void setValidFlag(String validFlag) {
        this.validFlag = validFlag;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getCustomCode() {
        return customCode;
    }
    public void setCustomCode(String customCode) {
        this.customCode = customCode;
    }
    public String getSpellCode() {
        return spellCode;
    }
    public void setSpellCode(String spellCode) {
        this.spellCode = spellCode;
    }
    public String getWbzxCode() {
        return wbzxCode;
    }
    public void setWbzxCode(String wbzxCode) {
        this.wbzxCode = wbzxCode;
    }
    public String getSortNo() {
        return sortNo;
    }
    public void setSortNo(String sortNo) {
        this.sortNo = sortNo;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public String getCreateOperator() {
        return createOperator;
    }
    public void setCreateOperator(String createOperator) {
        this.createOperator = createOperator;
    }
    public String getModifyTime() {
        return modifyTime;
    }
    public void setModifyTime(String modifyTime) {
        this.modifyTime = modifyTime;
    }
    public String getModifyOperator() {
        return modifyOperator;
    }
    public void setModifyOperator(String modifyOperator) {
        this.modifyOperator = modifyOperator;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getHealthArchiveNo() {
        return healthArchiveNo;
    }
    public void setHealthArchiveNo(String healthArchiveNo) {
        this.healthArchiveNo = healthArchiveNo;
    }
}

+ 15 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/PrescriptionController.java

@ -324,6 +324,21 @@ public class PrescriptionController extends BaseController{
			return Result.error(ex.getMessage());
		}
	}
	
	@RequestMapping(value = "getDataStatus",method = RequestMethod.POST)
	@ApiOperation("获取长处方相关数据状态接口")
	public Result affirmCARecipe(@ApiParam(name="type",value="数据类型:1:挂号数据;2:处方数据;3:结算数据",defaultValue = "")
	                             @RequestParam(value = "type",required = true) String type,
	                             @ApiParam(name="prescriptionCode",value="长处方单号",defaultValue = "")
	                             @RequestParam(value = "prescriptionCode",required = true) String prescriptionCode){
		try {
			String re = prescriptionService.getDataStatus(type,prescriptionCode);
			return Result.success("查询成功!",re);
		} catch (Exception ex) {
			ex.printStackTrace();
			return Result.error(ex.getMessage());
		}
	}
	/************************************ CA认证 ************************************************************/
	@RequestMapping(value = "RequestRealNameSoftCertAndSign",method = RequestMethod.POST)

+ 23 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java

@ -101,6 +101,29 @@ public class SignController {
            }
        }
    }
    
    @RequestMapping(value = "getSickMedicalSimpleListInfo",method = RequestMethod.POST)
    @ApiOperation("查询老年人体检记录接口")
    public Result getSickMedicalSimpleListInfo (
            @ApiParam(name="TIME_START",value="修改的开始时间",defaultValue = "2017-6-6 00:00:00")
            @RequestParam(value="TIME_START",required = false) String TIME_START,
            @ApiParam(name="TIME_END",value="修改的开始时间",defaultValue = "2017-6-7 23:59:59")
            @RequestParam(value="TIME_END",required = false) String TIME_END){
        try {
            String response = signZYService.getSickMedicalSimpleListInfo(TIME_START,TIME_END);
            return Result.success("查询成功!",response);
        } catch (Exception ex) {
            ex.printStackTrace();
            if(ex instanceof ApiException)
            {
                ApiException apiEx = (ApiException) ex;
                return Result.error(apiEx.errorCode(),ex.getMessage());
            }
            else{
                return Result.error(ex.getMessage());
            }
        }
    }

+ 12 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/SignZYService.java

@ -160,4 +160,16 @@ public class SignZYService {
        String response = zysoftService.getSickFamilyDoctorSpecialistControlByIdcard(identity_card_no,hospitalMapping[0],hospitalMapping[1]);
        return response;
    }
    
    /**
     * 查询老年人体检记录接口
     * @param time_start
     * @param time_end
     * @return
     */
	public String getSickMedicalSimpleListInfo(String time_start, String time_end) throws Exception{
        String[] hospitalMapping = getHospitalMapping(null); //获取机构映射
        String response = zysoftService.getSickMedicalSimpleListInfo(time_start,time_end,hospitalMapping[0],hospitalMapping[1]);
        return response;
	}
}

+ 19 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java

@ -796,4 +796,23 @@ public class ZysoftService {
        return response;
    }
    /**
     * 查询老年人体检记录接口
     * @param time_start
     * @param time_end
     * @return
     */
	public String getSickMedicalSimpleListInfo(String time_start, String time_end, String hospital,String licence) throws Exception{
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        
        Map<String,String> params = new HashMap<>();
        params.put("TIME_START",time_start);
        params.put("TIME_END",time_end);
        
        String response = postSecond("getSickMedicalSimpleListInfo","查询老年人体检记录接口",params,header,false);
        
        return response;
	}
}

+ 33 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java

@ -1139,4 +1139,37 @@ public class PrescriptionService extends ZysoftBaseService{
        //添加日志
        return addZyPushLog(data,"cancelPrescription","接收订单退费消息",error,"POST",status,"1",errMsg);
    }
    
    /**
     * 获取长处方相关数据状态接口
     * @param type 数据类型:1:挂号数据;2:处方数据;3:结算数据
     * @param prescriptionCode 长处方CODE
     * @return
     */
    public String getDataStatus(String type, String prescriptionCode)  throws Exception{
        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
        String[] hospitalMapping = getHospitalMapping(prescription.getHospital()); //获取机构映射
        String hospital = hospitalMapping[0];
        String licence = hospitalMapping[1];
    
        Map<String,String> header = new HashMap<>();
        header.put("ORGCODE",hospital);
        header.put("LICENCE",licence);
        
        String id = "";
        
        if("1".equals(type)){
            id = prescription.getVisitNo();
        }else if("2".equals(type)){
            id = prescription.getRecipeNo();
        }else{}
    
        Map<String,String> params = new HashMap<>();
        params.put("type",type);
        params.put("id",id);
    
        String response = postSecond("getDataStatus","获取长处方相关数据状态接口",params,null,header,false,2,"2");
    
        return response;
    }
}

+ 17 - 1
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java

@ -99,6 +99,14 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                logger.info("zy_execute_sick_settle_job reorder job job exist");
            }
            //处理当天支付,页面回调及异步回调失败的支付,每3分钟一次去主动查询并保存
            if (!quartzHelper.isExistJob("prescription_pay_query_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("prescription_pay_query_job");
                quartzHelper.addJob(PrescriptionPayQueryJob.class, trigger, "prescription_pay_query_job", new HashMap<String, Object>());
                logger.info("prescription_pay_query_job reorder job job success");
            } else {
                logger.info("prescription_pay_query_job reorder job job exist");
            }
            //居民24小时未回复的咨询自动关闭 每小时59分开始执行一次
            if (!quartzHelper.isExistJob("finish_consult_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("finish_consult_job");
@ -125,7 +133,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
            } else {
                logger.info("patient_disease_contion_syn_job  job exist");
            }
    
            //查询家庭签约支付结果,补更新医保签约号,3分钟跑一次
            if (!quartzHelper.isExistJob("sign_family_pay_result_migisterno_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("sign_family_pay_result_migisterno_job");
@ -134,6 +142,14 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
            } else {
                logger.info("sign_family_pay_result_migisterno_job  job exist");
            }
            //处理家庭签约当天支付,页面回调及异步回调失败的支付,每3分钟一次去主动查询并保存
            if (!quartzHelper.isExistJob("onepay_query_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("onepay_query_job");
                quartzHelper.addJob(OnePayQueryJob.class, trigger, "onepay_query_job", new HashMap<String, Object>());
                logger.info("onepay_query_job  job success");
            } else {
                logger.info("onepay_query_job  job exist");
            }

+ 55 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/OnePayQueryJob.java

@ -0,0 +1,55 @@
package com.yihu.wlyy.job;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.service.app.charge.OnePayService;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
 * 处理家庭签约当天支付,页面回调及异步回调失败的支付,每3分钟一次去主动查询并保存
 * Created by Reece on 2017/9/26/029.
 */
public class OnePayQueryJob implements Job {
    private static final Logger logger = LoggerFactory.getLogger(OnePayQueryJob.class);
    @Autowired
    private ChargeDao chargeDao;
    @Autowired
    private OnePayService payService;
    @Autowired
    WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("OnePayQueryJob start ..........");
        try {
            String accesstoken =  weiXinAccessTokenUtils.getAccessToken();
            //获取支付成功,回调失败的支付记录
            List<String> codeList = chargeDao.findTodayUnpay();
            if (!codeList.isEmpty()) {
                for (String code : codeList) {
                    try {
                        payService.chargeQuery(code,accesstoken);
                    } catch (Exception e) {
                        logger.info("OnePayQueryJob error ..........continue this JOB,CODE:" + code + ",message:" + e.getMessage());
                        continue;
                    }
                }
            }
            logger.info("OnePayQueryJob end ..........");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("OnePayQueryJob error ..........,message:" + e.getMessage());
        }
    }
}

+ 36 - 30
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PrenatalInspectorJob.java

@ -1,30 +1,36 @@
//package com.yihu.wlyy.job;
//
//import com.yihu.wlyy.service.app.prenatalInspector.PrenatalInspectorPreCardService;
//import com.yihu.wlyy.util.DateUtil;
//import org.quartz.Job;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.context.support.SpringBeanAutowiringSupport;
//
//import java.util.Date;
//
///**
// * 产检提醒(1预约提醒,2就诊提醒)
// * Created by yeshijie on 2017/6/7.
// */
//public class PrenatalInspectorJob implements Job{
//
//    @Autowired
//    private PrenatalInspectorPreCardService preCardService;
//
//    @Override
//    public void execute(JobExecutionContext context) throws JobExecutionException {
//        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
//        System.out.print("prenatal inspector wx message sending...");
//        String date = DateUtil.dateToStrShort(new Date());
//        //发送产检微信模板提醒消息
//        preCardService.sendPrenatalInspectorRemind();
//    }
//}
package com.yihu.wlyy.job;
import com.yihu.wlyy.service.app.prenatalInspector.PrenatalInspectorPreCardService;
import com.yihu.wlyy.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.util.Date;
/**
 * 产检提醒(1预约提醒,2就诊提醒)
 * Created by yeshijie on 2017/6/7.
 */
public class PrenatalInspectorJob implements Job{
    private static Logger logger = LoggerFactory.getLogger(PrenatalInspectorJob.class);
    @Autowired
    private PrenatalInspectorPreCardService preCardService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        logger.info("prenatal inspector wx message sending start...");
        String date = DateUtil.dateToStrShort(new Date());
        //发送产检微信模板提醒消息
        preCardService.sendPrenatalInspectorRemind();
        logger.info("prenatal inspector wx message sending end...");
    }
}

+ 57 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PrescriptionPayQueryJob.java

@ -0,0 +1,57 @@
package com.yihu.wlyy.job;
import com.yihu.wlyy.repository.prescription.PrescriptionPayDao;
import com.yihu.wlyy.service.app.prescription.PatientPrescriptionPayService;
import com.yihu.wlyy.service.app.prescription.PrescriptionService;
import com.yihu.wlyy.service.third.jw.JwPrescriptionService;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
 * 处理当天支付,页面回调及异步回调失败的支付,每3分钟一次去主动查询并保存
 * Created by Reece on 2017/8/29/029.
 */
public class PrescriptionPayQueryJob implements Job {
    private static final Logger logger = LoggerFactory.getLogger(PrescriptionPayQueryJob.class);
    @Autowired
    private PrescriptionPayDao prescriptionPayDao;
    @Autowired
    private PatientPrescriptionPayService payService;
    @Autowired
    WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("PrescriptionPayQueryJob start ..........");
        try {
            String accesstoken =  weiXinAccessTokenUtils.getAccessToken();
            //获取支付完成,院内结算失败的 处方CODE 集合
            List<String> prescriptionCodeList = prescriptionPayDao.findTodayUnpay();
            if (!prescriptionCodeList.isEmpty()) {
                for (String code : prescriptionCodeList) {
                    try {
                        payService.chargeQuery(code,accesstoken);
                    } catch (Exception e) {
                        logger.info("PrescriptionPayQueryJob error ..........continue this JOB,CODE:" + code + ",message:" + e.getMessage());
                        continue;
                    }
                }
            }
            logger.info("PrescriptionPayQueryJob end ..........");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("PrescriptionPayQueryJob error ..........,message:" + e.getMessage());
        }
    }
}

+ 5 - 1
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/charge/ChargeDao.java

@ -59,7 +59,11 @@ public interface ChargeDao extends PagingAndSortingRepository<WlyyCharge, Long>,
    int updateByChargeCode(String chargeCode, String chargeTime, Date updateTime, Integer totalAmount, Integer insuranceAmount, Integer selfPayAmount, String billNo, String miRegisterNo,String tradeStatus);
    List<WlyyCharge> findByPatient(String patient, Pageable pageRequest);
    
    @Query(value = "select * from wlyy_charge where trade_status = ?1 AND (mi_register_no IS null OR mi_register_no = '') AND update_time BETWEEN ?2  and ?3",nativeQuery = true)
    List<WlyyCharge> findByTradeStatusAndMiRegisterNoAndUpdateTime(int tradestatus, Date enddate, Date startdate);
    //   查询当天支付,页面回调及异步回调均失败的支付 tradeStatus为空
    @Query(value = "SELECT t.`code` FROM wlyy_charge t WHERE t.trade_status is null AND t.create_time >= date(now()) AND t.create_time < DATE_ADD(date(now()), INTERVAL 1 DAY)", nativeQuery = true)
    List<String> findTodayUnpay();
}

+ 20 - 20
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanDao.java

@ -1,20 +1,20 @@
//package com.yihu.wlyy.repository.patient;
//
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by yeshijie on 2017/6/6.
// */
//public interface PrenatalInspectorPlanDao extends PagingAndSortingRepository<PrenatalInspectorPlan, Long>{
//
//    @Query("select a from PrenatalInspectorPlan a where a.inspectionCode = ?1 and a.status = '0' ")
//    List<PrenatalInspectorPlan> findByCode(String inspectionCode);
//
//    @Query("select a from PrenatalInspectorPlan a where a.inspectionTime is not null and a.status = '0' and ( TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=7 or TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=1 ) ")
//    List<PrenatalInspectorPlan> findWxTipList();
//}
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yeshijie on 2017/6/6.
 */
public interface PrenatalInspectorPlanDao extends PagingAndSortingRepository<PrenatalInspectorPlan, Long>{
    @Query("select a from PrenatalInspectorPlan a where a.inspectionCode = ?1 and a.status = '0' ")
    List<PrenatalInspectorPlan> findByCode(String inspectionCode);
    @Query("select a from PrenatalInspectorPlan a where a.inspectionTime is not null and a.status = '0' and ( TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=7 or TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=1 ) ")
    List<PrenatalInspectorPlan> findWxTipList();
}

+ 20 - 20
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanLibraryDao.java

@ -1,20 +1,20 @@
//package com.yihu.wlyy.repository.patient;
//
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by yeshijie on 2017/6/6.
// */
//public interface PrenatalInspectorPlanLibraryDao extends PagingAndSortingRepository<PrenatalInspectorPlanLibrary, Long>{
//
//
//    @Query("select a from PrenatalInspectorPlanLibrary a where a.endDay >= ?1 ")
//    List<PrenatalInspectorPlanLibrary> findByDays(Long endDay);
//
//}
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yeshijie on 2017/6/6.
 */
public interface PrenatalInspectorPlanLibraryDao extends PagingAndSortingRepository<PrenatalInspectorPlanLibrary, Long>{
    @Query("select a from PrenatalInspectorPlanLibrary a where a.endDay >= ?1 ")
    List<PrenatalInspectorPlanLibrary> findByDays(Long endDay);
}

+ 17 - 17
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPreCardDao.java

@ -1,17 +1,17 @@
//package com.yihu.wlyy.repository.patient;
//
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPreCard;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by yeshijie on 2017/6/6.
// */
//public interface PrenatalInspectorPreCardDao extends PagingAndSortingRepository<PrenatalInspectorPreCard, Long>{
//
//    @Query("select a from PrenatalInspectorPreCard a where a.patient = ?1 and a.del='1' order by a.lastMenstrualDate desc")
//    List<PrenatalInspectorPreCard> findByPatient(String patient);
//}
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPreCard;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yeshijie on 2017/6/6.
 */
public interface PrenatalInspectorPreCardDao extends PagingAndSortingRepository<PrenatalInspectorPreCard, Long>{
    @Query("select a from PrenatalInspectorPreCard a where a.patient = ?1 and a.del='1' order by a.lastMenstrualDate desc")
    List<PrenatalInspectorPreCard> findByPatient(String patient);
}

+ 8 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionPayDao.java

@ -13,4 +13,12 @@ import java.util.List;
public interface PrescriptionPayDao extends PagingAndSortingRepository<PrescriptionPay, Long>, JpaSpecificationExecutor<PrescriptionPay> {
    @Query("from PrescriptionPay p where p.prescriptionCode=?1 ")
    PrescriptionPay findByPrescriptionPay(String prescriptionCode);
    //查询支付记录
    @Query("from PrescriptionPay p where p.code=?1 ")
    PrescriptionPay findByCode(String code);
    //   查询当天支付,页面回调及异步回调均失败的支付 tradeStatus为空
    @Query(value = "SELECT t.`code` FROM wlyy_prescription_pay t WHERE t.trade_status is null AND t.create_time >= date(now()) AND t.create_time < DATE_ADD(date(now()), INTERVAL 1 DAY)", nativeQuery = true)
    List<String> findTodayUnpay();
}

+ 12 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/ylz/PayLogDao.java

@ -0,0 +1,12 @@
package com.yihu.wlyy.repository.ylz;
import com.yihu.wlyy.entity.ylz.PayLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/9/20.
 */
public interface PayLogDao extends PagingAndSortingRepository<PayLog, Long>,JpaSpecificationExecutor<PayLog> {
}

+ 251 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/charge/OnePayService.java

@ -0,0 +1,251 @@
package com.yihu.wlyy.service.app.charge;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.entity.ylz.PayConfigura;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.ylz.PayConfiguraDao;
import com.yihu.wlyy.service.third.ylz.PayLogService;
import com.yihu.wlyy.util.SystemConf;
import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.domain.RequestParams;
import com.ylzinfo.onepay.sdk.domain.ResponseParams;
import com.ylzinfo.onepay.sdk.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 易联众统一支付服务类
 * add by hzp at 20170523
 */
@Service
@Transactional
public class OnePayService {
    @Autowired
    private PayConfiguraDao configuraDao;
    private String signType = "MD5";
    private String encryptType = "AES";
    @Autowired
    private HospitalMappingDao hospitalMappingDao;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    ChargeDao chargeDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SignFamilyDao signFamilyDao;
    @Autowired
    DoctorDao doctorDao;
    @Value("${server.server_url}")
    private String serverUrl;
    @Value("${wechat.accId}")
    private String accId;
    Properties systemConf = SystemConf.getInstance().getSystemProperties();
    private static final Logger LOGGER = LoggerFactory.getLogger(OnePayService.class);
    /**
     * 家庭医生签约支付查询
     */
    public String chargeQuery(String code, String accessToken) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = null;
        PayConfigura config = configuraDao.findWorkConfigura();
        try {
            WlyyCharge charge = chargeDao.findByCode(code);
            HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
//            requestParams.setAppId(appId);
            requestParams.setAppId(hospitalMapping.getAppId());
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeQueryType());
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", code);  //接入应用结算业务流水号
            params.put("wxToken", accessToken);
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
                result = JSON.toJSONString(res.getParam());
//                 新增保存数据
                JSONObject request = JSON.parseObject(result);
                String chargeStatus = request.getString("chargeStatus");//交易状态
                String chargeNo = request.getString("chargeNo");//支付平台流水号
                String chargeTime = request.getString("chargeTime");//支付平台交易成功时间
                String outChargeNo = request.getString("outChargeNo");//接入应用业务流水号
                String outChargeTime = request.getString("outChargeTime");//接入应用时间
                String medOrgNo = request.getString("medOrgNo");//医疗机构编号
                String medOrgName = request.getString("medOrgName");//医疗机构名称
                String billNo = request.getString("billNo");//待结算费用单据号
                String cardNo = request.getString("cardNo");//医保卡号
                String totalAmount = request.getString("totalAmount");//交易总金额
                String insuranceAmount = request.getString("insuranceAmount");//医保支付金额
                String selfPayAmount = request.getString("selfPayAmount");//自付金额
                String userId = request.getString("userId");//用户openID
                String userName = request.getString("userName");//用户名字
                String idType = request.getString("idType");//证件类型
                String idNo = request.getString("idNo");//证件号码
//                String appId = request.getString("appId");
//                String channel = request.getString("channel");//支付方式
//                String sign = request.getString("sign");
//                String signType = request.getString("signType");
//                String timestamp = request.getString("timestamp");
                JSONObject responseContents = request.getJSONObject("responseContent");//医保结构体
                WlyyCharge chargePay = chargeDao.findByCode(outChargeNo);
                if (responseContents != null) {
                    String miRegisterNo = null;//医保挂号
                    String miCollectDate = null;//收费日期
                    String miCollectTime = null;//收费时间
                    String miSettleNo = null;//医保收费单据号 (医保签约号)
                    String miCollectStatus = null;//扣费状态
                    String miRegisterStatus = null;//登记状态
                    String cadresPay = "0";//公务员补助
                    String miTotalFee = "0";//本次报销总额
                    String healthCarePay = "0";//保健基金支付
                    String heathPay = "0";//健康账户支付
                    String accountPay = "0";//个人账户支付
                    String selfPay = "0";//个人现金支付
                    String civilPay = "0";//民政补助金额
                    if (responseContents.containsKey(miRegisterNo)) {
                        miRegisterNo = responseContents.getString("miRegisterNo");
                    }
                    if (responseContents.containsKey(miCollectDate)) {
                        miCollectDate = responseContents.getString("miCollectDate");
                    }
                    if (responseContents.containsKey(miCollectTime)) {
                        miCollectTime = responseContents.getString("miCollectTime");
                    }
                    if (responseContents.containsKey(miSettleNo)) {
                        miSettleNo = responseContents.getString("miSettleNo");
                    }
                    if (responseContents.containsKey(miCollectStatus)) {
                        miCollectStatus = responseContents.getString("miCollectStatus");
                    }
                    if (responseContents.containsKey(miRegisterStatus)) {
                        miRegisterStatus = responseContents.getString("miRegisterStatus");
                    }
                    if (responseContents.containsKey(cadresPay)) {
                        cadresPay = responseContents.getString("cadresPay");
                    }
                    if (responseContents.containsKey(miTotalFee)) {
                        miTotalFee = responseContents.getString("miTotalFee");
                    }
                    if (responseContents.containsKey(healthCarePay)) {
                        healthCarePay = responseContents.getString("healthCarePay");
                    }
                    if (responseContents.containsKey(heathPay)) {
                        heathPay = responseContents.getString("heathPay");
                    }
                    if (responseContents.containsKey(accountPay)) {
                        accountPay = responseContents.getString("accountPay");
                    }
                    if (responseContents.containsKey(selfPay)) {
                        selfPay = responseContents.getString("selfPay");
                    }
                    if (responseContents.containsKey(civilPay)) {
                        civilPay = responseContents.getString("civilPay");
                    }
                    chargePay.setMiRegisterNo(miRegisterNo);//医保挂号
                    chargePay.setMiCollectDate(miCollectDate);
                    chargePay.setMiCollectTime(miCollectTime);
                    chargePay.setMiSettleNo(miSettleNo);
                    chargePay.setMiCollectStatus(miCollectStatus);
                    chargePay.setMiRegisterStatus(miRegisterStatus);
                    chargePay.setCadresPay(cadresPay);
                    chargePay.setMiTotalFee(miTotalFee);
                    chargePay.setHealthCarePay(healthCarePay);
                    chargePay.setHeathPay(heathPay);
                    chargePay.setAccountPay(accountPay);
                    chargePay.setSelfPay(selfPay);
                    chargePay.setCivilPay(civilPay);
                }
                if ("0".equals(chargeStatus) || "SUCCESS".equals(chargeStatus)) {
                    chargePay.setTradeStatus("1");//交易状态 成功1 失败0
                } else {
                    chargePay.setTradeStatus("0");//交易状态 成功1 失败0
                }
                chargePay.setChargeNo(chargeNo);//支付流水号
                SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmmss");
                chargePay.setChargeTime(chargeTime);//支付平台交易成功时间
                chargePay.setCreateTime(formatDate.parse(outChargeTime));//接入应用内业务时间
                chargePay.setMedOrgNo(medOrgNo);//医疗机构编号
                chargePay.setMedOrgName(medOrgName);//医疗机构名称
                chargePay.setBillNo(billNo);//待结算费用单据号
                chargePay.setSsc(cardNo);//医保卡号
                chargePay.setTotalAmount(Integer.parseInt(totalAmount));//交易总金额
                chargePay.setInsuranceAmount(Integer.parseInt(insuranceAmount));//医保支付金额
                chargePay.setSelfpayAmount(Integer.parseInt(selfPayAmount));//自付金额
                chargePay.setOpenid(userId);
                chargePay.setName(userName);
                chargePay.setIdType(idType);//证件类型
                chargePay.setIdNo(idNo);//证件号码
                //        保存数据库更改记录
                chargeDao.save(chargePay);
                LOGGER.info("请求成功,返回参数: " + result);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
}

+ 85 - 240
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java

@ -1,240 +1,85 @@
//package com.yihu.wlyy.service.app.prenatalInspector;
//
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
//import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPreCard;
//import com.yihu.wlyy.repository.patient.PatientDao;
//import com.yihu.wlyy.repository.patient.PrenatalInspectorPlanDao;
//import com.yihu.wlyy.repository.patient.PrenatalInspectorPlanLibraryDao;
//import com.yihu.wlyy.repository.patient.PrenatalInspectorPreCardDao;
//import com.yihu.wlyy.service.BaseService;
//import com.yihu.wlyy.service.app.sign.FamilyContractService;
//import com.yihu.wlyy.task.PushMsgTask;
//import com.yihu.wlyy.util.DateUtil;
//import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.json.JSONArray;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
///**
// * Created by yeshijie on 2017/6/6.
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class PrenatalInspectorPreCardService extends BaseService {
//
//    @Autowired
//    private PrenatalInspectorPreCardDao prenatalInspectorPreCardDao;
//    @Autowired
//    private PrenatalInspectorPlanLibraryDao prenatalInspectorPlanLibraryDao;
//    @Autowired
//    private PrenatalInspectorPlanDao prenatalInspectorPlanDao;
//    @Autowired
//    private WeiXinAccessTokenUtils accessTokenUtils;
//    @Autowired
//    private PatientDao patientDao;
//    @Autowired
//    private FamilyContractService familyContractService;
//
//    /**
//     * 待产检计划
//     * @param code
//     * @return
//     */
//    public JSONArray planList(String code){
//        JSONArray jsonArray = new JSONArray();
//        List<PrenatalInspectorPlan> planList = prenatalInspectorPlanDao.findByCode(code);
//        for (PrenatalInspectorPlan plan:planList){
//            JSONObject json = new JSONObject();
//            json.put("checkItem",plan.getCheckItem());
//            json.put("name",plan.getName());
//            json.put("thisFoucs",plan.getThisFocus());
//            json.put("thisNote",plan.getThisNote());
//            if(plan.getInspectionTime()==null){
//                json.put("inspectionTime","");
//            }else {
//                json.put("inspectionTime",DateUtil.dateToStrShort(plan.getInspectionTime()));
//            }
//            json.put("inspectionEndTime",DateUtil.dateToStrShort(plan.getInspectionEndTime()));
//            json.put("inspectionStartTime",DateUtil.dateToStrShort(plan.getInspectionStartTime()));
//
//
//            jsonArray.put(json);
//        }
//
//
//        return jsonArray;
//    }
//
//    /**
//     * 预建卡列表-孕检计划
//     * @param patient
//     * @return
//     */
//    public JSONArray preCardList(String patient){
//        JSONArray jsonArray = new JSONArray();
//        List<PrenatalInspectorPreCard> preCards = prenatalInspectorPreCardDao.findByPatient(patient);
//        for (PrenatalInspectorPreCard preCard:preCards){
//            JSONObject json = new JSONObject();
//            json.put("code",preCard.getCode());
//            json.put("dueDate",DateUtil.dateToStrShort(preCard.getDueDate()));//预产期
//            Date date = new Date();
//            Long dueDateDay = DateUtil.getDays(preCard.getDueDate(),date);
//            if(dueDateDay>0){
//                json.put("dueDateWeek",getWeek(dueDateDay.intValue()));//距离预产期周数
//                json.put("dueDateDay",getDay(dueDateDay.intValue()));//距离预产期周数的余数
//                Long pregnancyDay = DateUtil.getDays(date,preCard.getLastMenstrualDate());
//                int week = getWeek(pregnancyDay.intValue());
//                int day = getDay(pregnancyDay.intValue());
//                String preDay = day==0?(week+"周"):(week+"周"+day+"天");//怀孕时间
//                json.put("status",preDay);
//            }else {
//                json.put("dueDateWeek",0);//距离预产期周数
//                json.put("dueDateDay",0);//距离预产期周数的余数
//                json.put("status",preCard.getStatus());
//            }
//
//            json.put("hospitalName",preCard.getHospitalName());//预约床位医院
//            json.put("orderBedTime",preCard.getOrderBedTime());//预约床位时间
//
//            jsonArray.put(json);
//        }
//
//        return jsonArray;
//    }
//
//    /**
//     * 把天数换算成周数
//     * @param day
//     * @return
//     */
//    private int getWeek(Integer day){
//        return day/7;
//    }
//
//    /**
//     * 把天数换算成周数的余数
//     * @param day
//     * @return
//     */
//    private int getDay(Integer day){
//        return day%7;
//    }
//
//    /**
//     * 新建产检预建卡
//     */
//    @Transactional
//    public void addPrenatalInspectorPreCard(PrenatalInspectorPreCard preCard){
//        //1、保存预建卡
//        Date date = new Date();
//        Date lastMenstrualDate = preCard.getLastMenstrualDate();
//        preCard.setDel("1");
//        preCard.setCode(getCode());
//        preCard.setCzrq(date);
//        preCard.setDueDate(DateUtil.getDueDate(preCard.getLastMenstrualDate()));//预产期
//        preCard.setStatus("0");
//        preCard.setEffective("");
//        preCard.setInspectionPhase("1");//检查阶段
//        prenatalInspectorPreCardDao.save(preCard);
//
//        String patient = preCard.getPatient();
//
//        //2、生成待产检计划
//        Long days = DateUtil.getDays(date,lastMenstrualDate);
//        List<PrenatalInspectorPlanLibrary> libraries = prenatalInspectorPlanLibraryDao.findByDays(days);
//        List<PrenatalInspectorPlan> plans = new ArrayList<>();
//        PrenatalInspectorPlan plan = null;
//        for (PrenatalInspectorPlanLibrary library:libraries){
//            plan = new PrenatalInspectorPlan();
//            plan.setInspectionPhase(library.getInspectionPhase());
//            plan.setStatus("0");
//            plan.setPatient(patient);
//            plan.setCzrq(date);
//            plan.setCheckItem(library.getCheckItem());
//            plan.setInspectionCode(preCard.getCode());
//            plan.setInspectionEndTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getEndDay().intValue()));
//            plan.setInspectionStartTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getStartDay().intValue()));
//            plan.setName(library.getName());
//            plan.setThisFocus(library.getThisFocus());
//            plan.setThisNote(library.getThisNote());
//
//            if("1".equals(plan.getInspectionPhase())){
//                SignFamily jiating = familyContractService.findByPatientByType(patient, 2);
//                if(jiating!=null){
//                    plan.setSignHospital(jiating.getHospital());
//                }
//            }
//
//            plans.add(plan);
//        }
//        if (plans.size()>0){
//            prenatalInspectorPlanDao.save(plans);
//        }
//
//    }
//
//    /**
//     * 产检提醒(1预约提醒,2就诊提醒)
//     * 1、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前7天(保证居民可自行预约),发出产检预约提醒通知。点击该消息,进入预约页面
//     * 2、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前1天,发出产检就诊提醒,提醒居民就诊。点击该消息,进入预约记录页面
//     */
//    public void sendPrenatalInspectorRemind(){
//        System.out.println("产检计划---running");
//        List<PrenatalInspectorPlan> planList = prenatalInspectorPlanDao.findWxTipList();
//        for (PrenatalInspectorPlan plan:planList){
//            try {
//                Patient patient = patientDao.findByCode(plan.getPatient());
//                String openId = patient.getOpenid();
//                String name = patient.getName();
//                String patientCode = patient.getCode();
//                if(StringUtils.isNotBlank(openId)){
//                    Long day = DateUtil.getDays(plan.getInspectionTime(),DateUtil.getNowDateShort());
//                    JSONObject json = new JSONObject();
//                    if(day==7){
//                        //产检提醒
//                        json.put("remark","产检内容以医生实际检查为准。点击进行预约");
//                        json.put("first",name+",您好!您和您的宝宝需要进行产检啦~请及时预约产检,如已预约,请忽略");
//                        if("1".equals(plan.getInspectionPhase())){
//                            if(StringUtils.isNotBlank(plan.getSignHospital())){
//                                json.put("url","wdyy/html/hospital-dept.html?openid="+openId+"&toUser="+patientCode+"&toName="+name+"&hospitalId="+plan.getSignHospital());
//                            }else {
//                                json.put("url","wdyy/html/appointment-register.html?openid="+openId+"&toUser="+patientCode+"&toName="+name+"&orderType=1");
//                            }
//                        }else {
//                            json.put("url","wdyy/html/appointment-register.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
//                        }
//
//                        json.put("keyword1","产检提醒");
//                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
//                        json.put("keyword2",keyword2);
//                        PushMsgTask.getInstance().sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
//                    }else if(day==1){
//                        //产检就诊提醒
//                        json.put("remark","产检内容以医生实际检查为准。点击查看预约记录");
//                        json.put("first",name+",您好!您和您的宝宝即将进行产检啦~请按时就诊,如已就诊,请忽略");
//                        json.put("url","wdyy/html/my-appointment.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
//                        json.put("keyword1","产检就诊提醒");
//                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
//                        json.put("keyword2",keyword2);
//                        PushMsgTask.getInstance().sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
//                    }
//                }
//            }catch (Exception e){
//                System.out.println("微信提醒发送失败");
//                e.printStackTrace();
//            }
//        }
//
//    }
//
//}
package com.yihu.wlyy.service.app.prenatalInspector;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PrenatalInspectorPlanDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by yeshijie on 2017/6/6.
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class PrenatalInspectorPreCardService extends BaseService {
    @Autowired
    private PrenatalInspectorPlanDao prenatalInspectorPlanDao;
    @Autowired
    private WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private PushMsgTask pushMsgTask;
    /**
     * 产检提醒(1预约提醒,2就诊提醒)
     * 1、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前7天(保证居民可自行预约),发出产检预约提醒通知。点击该消息,进入预约页面
     * 2、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前1天,发出产检就诊提醒,提醒居民就诊。点击该消息,进入预约记录页面
     */
    public void sendPrenatalInspectorRemind(){
        System.out.println("产检计划---running");
        List<PrenatalInspectorPlan> planList = prenatalInspectorPlanDao.findWxTipList();
        for (PrenatalInspectorPlan plan:planList){
            try {
                Patient patient = patientDao.findByCode(plan.getPatient());
                String openId = patient.getOpenid();
                String name = patient.getName();
                String patientCode = patient.getCode();
                if(StringUtils.isNotBlank(openId)){
                    Long day = DateUtil.getDays(plan.getInspectionTime(),DateUtil.getNowDateShort());
                    JSONObject json = new JSONObject();
                    if(day==7){
                        //产检提醒
                        json.put("remark","产检内容以医生实际检查为准。点击进行预约");
                        json.put("first",name+",您好!您和您的宝宝需要进行产检啦~请及时预约产检,如已预约,请忽略");
                        json.put("url","wdyy/html/appointment-register.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
                        json.put("keyword1","产检提醒");
                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
                        json.put("keyword2",keyword2);
                        pushMsgTask.sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
                    }else if(day==1){
                        //产检就诊提醒
                        json.put("remark","产检内容以医生实际检查为准。点击查看预约记录");
                        json.put("first",name+",您好!您和您的宝宝即将进行产检啦~请按时就诊,如已就诊,请忽略");
                        json.put("url","wdyy/html/my-appointment.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
                        json.put("keyword1","产检就诊提醒");
                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
                        json.put("keyword2",keyword2);
                        pushMsgTask.sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
                    }
                }
            }catch (Exception e){
                System.out.println("微信提醒发送失败");
                e.printStackTrace();
            }
        }
    }
}

+ 304 - 37
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prescription/PatientPrescriptionPayService.java

@ -1,17 +1,35 @@
package com.yihu.wlyy.service.app.prescription;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.prescription.*;
import com.yihu.wlyy.entity.security.AccessToken;
import com.yihu.wlyy.entity.ylz.PayConfigura;
import com.yihu.wlyy.entity.zydict.ZyPushLog;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.prescription.PrescriptionDao;
import com.yihu.wlyy.repository.prescription.PrescriptionExpressageDao;
import com.yihu.wlyy.repository.prescription.PrescriptionInfoDao;
import com.yihu.wlyy.repository.prescription.PrescriptionPayDao;
import com.yihu.wlyy.repository.ylz.PayConfiguraDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.service.weixin.wxpay.common.Configure;
import com.yihu.wlyy.util.SystemConf;
import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.domain.RequestParams;
@ -22,9 +40,18 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
/**
@ -34,47 +61,286 @@ import java.util.*;
@Service
public class PatientPrescriptionPayService extends BaseService {
    private Logger logger = LoggerFactory.getLogger(PatientPrescriptionPayService.class);
    private Logger logger=LoggerFactory.getLogger(PatientPrescriptionPayService.class);
    //公共配置文件
    Properties systemConf = SystemConf.getInstance().getSystemProperties();
    //    各环境对应配置
    @Value("${server.server_url}")
    private String serverUrl;
    
    //    Java配置文件 后续删除
    private String signType = "MD5";
    private String encryptType = "AES";
    
    @Value("${wechat.accId}")
    private String accId;
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Value("${wechat.accId}")
    private String accId;
    
    //    Java配置文件 后续删除
    private String signType = "MD5";
    private String encryptType = "AES";
    //    引入实例
    @Autowired
    private Configure config;
    
    private PayConfiguraDao configuraDao;
    @Autowired
    private PrescriptionPayDao payDao;
    @Autowired
    private HospitalMappingDao mappingDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private ChargeDao chargeDao;
    
    @Autowired
    private SignFamilyDao signFamilyDao;
    
    @Autowired
    private HospitalMappingDao hospitalMappingDao;
    
    @Autowired
    private AccessTokenService accessTokenService;
    
    @Autowired
    private com.yihu.wlyy.util.HttpUtil HttpUtil;
    
    
    @Autowired
    private PrescriptionExpressageDao expressageDao;
    /**
     * 家庭医生签约支付查询
     */
    public String chargeQuery(String code, String accessToken) throws Exception {
        PayConfigura config = configuraDao.findWorkConfigura();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        int flag = 0;
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = null;
        try {
            PrescriptionPay charge = payDao.findByCode(code);
            String prescriptionCode = charge.getPrescriptionCode();
            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
            HospitalMapping hospitalMapping = mappingDao.findByCode(prescription.getHospital());
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
//            requestParams.setAppId(appId);
            requestParams.setAppId(hospitalMapping.getAppId());
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeQueryType());
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", code);  //接入应用结算业务流水号
            params.put("wxToken", accessToken);
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
                flag = 1;
                result = JSON.toJSONString(res.getParam());
//             新增保存数据
                JSONObject request = JSON.parseObject(result);
                String chargeStatus = request.getString("chargeStatus");//交易状态
                String chargeNo = request.getString("chargeNo");//支付平台流水号
                String chargeTime = request.getString("chargeTime");//支付平台交易成功时间
                String outChargeNo = request.getString("outChargeNo");//接入应用业务流水号
                String outChargeTime = request.getString("outChargeTime");//接入应用时间
                String medOrgNo = request.getString("medOrgNo");//医疗机构编号
                String medOrgName = request.getString("medOrgName");//医疗机构名称
                String billNo = request.getString("billNo");//待结算费用单据号
                String cardNo = request.getString("cardNo");//医保卡号
                String totalAmount = request.getString("totalAmount");//交易总金额
                String insuranceAmount = request.getString("insuranceAmount");//医保支付金额
                String selfPayAmount = request.getString("selfPayAmount");//自付金额
                String userId = request.getString("userId");//用户openID
                String userName = request.getString("userName");//用户名字
                String idNo = request.getString("idNo");//证件号码
                String idType = request.getString("idType");//证件类型
//                String appId = request.getString("appId");
//                String channel = request.getString("channel");//支付方式
//                String sign = request.getString("sign");
//                String signType = request.getString("signType");
//                String timestamp = request.getString("timestamp");
                JSONObject responseContents = request.getJSONObject("responseContent");//医保结构体
                PrescriptionPay prescriptionPay = payDao.findByCode(outChargeNo);
                if (responseContents != null) {
                    String miSettleNo = null;//医保收费单据号 (医保签约号)
                    String miRegisterNo = null;//医保挂号
                    String miCollectDate = null;//收费日期
                    String miCollectTime = null;//收费时间
                    String miCollectorName = null;//收费人姓名
                    String miTotalFee = "0";//本次报销总额
                    String selfPay = "0";//个人现金支付
                    String accountPay = "0";//个人账户支付
                    String heathPay = "0";//健康账户支付
                    String cadresPay = "0";//公务员补助
                    String fundPay = "0";//基金支付
                    String healthCarePay = "0";//保健基金支付
                    String commercePay = "0";//商业保险支付
                    String familyPay = "0";//共济账户支付
                    String civilPay = "0";//民政补助金额
                    String civilZone = null;//民政行政区号
                    String bdrugPay = "0";//乙类支付金额
                    String unlessAmount = "0";//非医保费用
                    String exceedAmount = "0";//超封顶线金额
                    String accountBalance = "0";//个人账户余额
                    String healthBalance = "0";//健康账户余额
                    if (responseContents.containsKey("miSettleNo")) {
                        miSettleNo = responseContents.getString("miSettleNo");
                    }
                    if (responseContents.containsKey("miRegisterNo")) {
                        miRegisterNo = responseContents.getString("miRegisterNo");
                    }
                    if (responseContents.containsKey("miCollectDate")) {
                        miCollectDate = responseContents.getString("miCollectDate");
                    }
                    if (responseContents.containsKey("miCollectTime")) {
                        miCollectTime = responseContents.getString("miCollectTime");
                    }
                    if (responseContents.containsKey("miCollectorName")) {
                        miCollectorName = responseContents.getString("miCollectorName");
                    }
                    if (responseContents.containsKey("miTotalFee")) {
                        miTotalFee = responseContents.getString("miTotalFee");
                    }
                    if (responseContents.containsKey("selfPay")) {
                        selfPay = responseContents.getString("selfPay");
                    }
                    if (responseContents.containsKey("accountPay")) {
                        accountPay = responseContents.getString("accountPay");
                    }
                    if (responseContents.containsKey("heathPay")) {
                        heathPay = responseContents.getString("heathPay");
                    }
                    if (responseContents.containsKey("cadresPay")) {
                        cadresPay = responseContents.getString("cadresPay");
                    }
                    if (responseContents.containsKey("fundPay")) {
                        fundPay = responseContents.getString("fundPay");
                    }
                    if (responseContents.containsKey("healthCarePay")) {
                        healthCarePay = responseContents.getString("healthCarePay");
                    }
                    if (responseContents.containsKey("commercePay")) {
                        commercePay = responseContents.getString("commercePay");
                    }
                    if (responseContents.containsKey("familyPay")) {
                        familyPay = responseContents.getString("familyPay");
                    }
                    if (responseContents.containsKey("civilPay")) {
                        civilPay = responseContents.getString("civilPay");
                    }
                    if (responseContents.containsKey("civilZone")) {
                        civilZone = responseContents.getString("civilZone");
                    }
                    if (responseContents.containsKey("bdrugPay")) {
                        bdrugPay = responseContents.getString("bdrugPay");
                    }
                    if (responseContents.containsKey("unlessAmount")) {
                        unlessAmount = responseContents.getString("unlessAmount");
                    }
                    if (responseContents.containsKey("exceedAmount")) {
                        exceedAmount = responseContents.getString("exceedAmount");
                    }
                    if (responseContents.containsKey("accountBalance")) {
                        accountBalance = responseContents.getString("accountBalance");
                    }
                    if (responseContents.containsKey("healthBalance")) {
                        healthBalance = responseContents.getString("healthBalance");
                    }
                    prescriptionPay.setMiSettleNo(miSettleNo);//医保收费单据号
                    prescriptionPay.setMiRegisterNo(miRegisterNo);//医保挂号
                    SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMdd");
                    prescriptionPay.setMiCollectDate(formatDate.parse(miCollectDate));//收费日期
                    SimpleDateFormat formatTime = new SimpleDateFormat("HHmm");
                    prescriptionPay.setMiCollectTime(formatTime.parse(miCollectTime));//收费时间
                    prescriptionPay.setMiCollectorName(miCollectorName);//收费人姓名
                    prescriptionPay.setMiTotalFee(Integer.parseInt(miTotalFee));//本次报销总额
                    prescriptionPay.setSelfPay(Integer.parseInt(selfPay));//个人现金支付
                    prescriptionPay.setAccountPay(Integer.parseInt(accountPay));//个人账户支付
                    prescriptionPay.setHeathPay(Integer.parseInt(heathPay));//健康账户支付
                    prescriptionPay.setCadresPay(Integer.parseInt(cadresPay));//公务员补助
                    prescriptionPay.setFundPay(Integer.parseInt(fundPay));//基金支付
                    prescriptionPay.setHealthCarePay(Integer.parseInt(healthCarePay));//保健基金支付
                    prescriptionPay.setCommercePay(Integer.parseInt(commercePay));//商业保险支付
                    prescriptionPay.setFamilyPay(Integer.parseInt(familyPay));//共济账户支付
                    prescriptionPay.setCivilPay(Integer.parseInt(civilPay));//民政补助金额
                    prescriptionPay.setCivilZone(civilZone);//民政行政区号
                    prescriptionPay.setBdrugPay(Integer.parseInt(bdrugPay));//乙类支付金额
                    prescriptionPay.setUnlessAmount(Integer.parseInt(unlessAmount));//非医保费用
                    prescriptionPay.setExceedAmount(Integer.parseInt(exceedAmount));//超封顶线金额
                    prescriptionPay.setAccountBalance(Integer.parseInt(accountBalance));//个人账户余额
                    prescriptionPay.setHealthBalance(Integer.parseInt(healthBalance));//健康账户余额
                }
                prescriptionPay.setTradeStatus(chargeStatus);
                prescriptionPay.setChargeNo(chargeNo);//支付流水号
                prescriptionPay.setChargeTime(format.parse(chargeTime));
                prescriptionPay.setOutChargeTime(format.parse(outChargeTime));
                prescriptionPay.setMedOrgNo(medOrgNo);
                prescriptionPay.setMedOrgName(medOrgName);
                prescriptionPay.setBillNo(billNo);
                prescriptionPay.setPrincipalCardNo(cardNo);
                prescriptionPay.setTotalAmount(Integer.parseInt(totalAmount));
                prescriptionPay.setInsuranceAmount(Integer.parseInt(insuranceAmount));//医保支付金额
                prescriptionPay.setSelfPayAmount(Integer.parseInt(selfPayAmount));//自付金额
                prescriptionPay.setOpenid(userId);
                prescriptionPay.setUserName(userName);
                prescriptionPay.setIdType(idType);
                prescriptionPay.setIdNo(idNo);
                //        保存数据库更改记录
                payDao.save(prescriptionPay);
                PrescriptionExpressage expressage = expressageDao.findByPrescriptionPay(prescriptionCode);
                if ("0".equals(chargeStatus) || "SUCCESS".equals(chargeStatus)) {
                    prescriptionPay.setTradeStatus("1");//交易状态 成功1 失败0
                    prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.pay_success.getValue());//续费状态 枚举 支付成功
                    expressage.setDel(1);//快递信息状态 1可用 0删除
                    expressageDao.save(expressage);
                    prescriptionDao.save(prescription);
                } else if ("1".equals(chargeStatus) || "FAIL".equals(chargeStatus)) {
                    prescriptionPay.setTradeStatus("0");//交易状态 成功1 失败0
                    prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.pay_error.getValue());////续费状态 支付失败
                    expressage.setDel(0);//快递信息状态 1可用 0删除
                    expressageDao.save(expressage);
                    prescriptionDao.save(prescription);
                }
                logger.info("请求成功,返回参数: " + result);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    public String getSignFamilyPayResult(String outChargeNo, String accessToken, String appId, String appSecret) throws Exception {
        PayConfigura config = configuraDao.findWorkConfigura();
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
@ -83,7 +349,7 @@ public class PatientPrescriptionPayService extends BaseService {
//      ***************************  测通流程 ***************************************
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
    
        try {
            RequestParams requestParams = new RequestParams();
            requestParams.setAppId(appId);
@ -91,12 +357,12 @@ public class PatientPrescriptionPayService extends BaseService {
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeQueryType());
        
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", outChargeNo);  //接入应用结算业务流水号
            params.put("wxToken", accessToken);
        
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
@ -104,12 +370,12 @@ public class PatientPrescriptionPayService extends BaseService {
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
        
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
                result = JSON.toJSONString(res.getParam());
            
//                logger.info("请求成功,返回参数: " + result);
            } else {
                isSuccess = false;
@ -122,7 +388,7 @@ public class PatientPrescriptionPayService extends BaseService {
            ex.printStackTrace(pw);
            error = sw.toString();
        }
    
        //type = 3易联众接口保存http日志
//        logger.info("api - " + config.getChargeQueryType());
//        logger.info("request - " + msgBody);
@ -132,10 +398,10 @@ public class PatientPrescriptionPayService extends BaseService {
        if (!isSuccess) {
            throw new Exception(error);
        }
    
        return result;
    }
    
    /**
     * 1.根据时间范围遍历没有医保签约号的家庭签约支付记录
     * 2.询家庭签约支付结果,补更新医保签约号
@ -143,33 +409,33 @@ public class PatientPrescriptionPayService extends BaseService {
     * @param enddate
     */
    public void getSignFamilyPayResultJob(Date startdate, Date enddate) throws Exception {
    
        //根据时间范围遍历没有医保签约号的家庭签约支付记录
        List<WlyyCharge> charges = chargeDao.findByTradeStatusAndMiRegisterNoAndUpdateTime(0,enddate,startdate);
        
        if(!charges.isEmpty()){
    
            logger.info("根据时间范围遍历没有医保签约号的家庭签约支付记录:"+charges.size()+"条");
            String accessToken = this.getAccessToken();
            for (WlyyCharge charge:charges) {
                try {
                    
                    //1.根据签约ID获取家庭签约记录,判断是否有效
                    SignFamily signFamily = signFamilyDao.findByCode(charge.getChargeRelation());
                    
                    if(1 == signFamily.getStatus()){
                        HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
                        String appid = hospitalMapping.getAppId();
                        String appsecert =  hospitalMapping.getAppSecret();
                        String signFamilyPayResultJson = this.getSignFamilyPayResult(charge.getCode(),"",appid,appsecert);
                        
                        if(StringUtils.isNotBlank(signFamilyPayResultJson)){
                            JSONObject reobj =  JSON.parseObject(signFamilyPayResultJson);
                            if(reobj.containsKey("responseContent")){
                                JSONObject responseContent = reobj.getJSONObject("responseContent");
                                
                                if(responseContent.containsKey("miRegisterNo") && StringUtils.isNotBlank(responseContent.getString("miRegisterNo"))){
                                        String miRegisterNo = responseContent.getString("miRegisterNo");
                                    String miRegisterNo = responseContent.getString("miRegisterNo");
                                    charge.setMiRegisterNo(miRegisterNo);
                                    charge.setNeedUpload("1");
                                    charge.setUpdateTime(new Date());
@ -177,18 +443,18 @@ public class PatientPrescriptionPayService extends BaseService {
                                }else{
                                    logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:miRegisterNo不存在");
                                }
                            
                            }else{
                                logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:responseContent不存在");
                            }
                        }else{
                            logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:接口无返回值");
                        }
                        
                    }else{
                        logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:对应的签约记录无效");
                    }
                    
                }catch (Exception e){
                    logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:" +e.getMessage());
                    continue;
@ -230,5 +496,6 @@ public class PatientPrescriptionPayService extends BaseService {
            return null;
        }
    }
}

+ 58 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/third/ylz/PayLogService.java

@ -0,0 +1,58 @@
package com.yihu.wlyy.service.third.ylz;
import com.yihu.wlyy.entity.ylz.PayLog;
import com.yihu.wlyy.repository.ylz.PayLogDao;
import com.yihu.wlyy.service.system.SystemDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
 * Created by Reece on 2017/9/20.
 * 日志服务
 */
@Service
public class PayLogService {
    @Autowired
    private PayLogDao payLogDao;
    @Autowired
    private SystemDictService systemDictService;
    public String onepayType = "0"; //0家庭签约支付
    public String onepayRecipeType = "1";     //1续方支付
    /**
     * 保存http调用日志  type 0家庭签约支付 1续方支付
     */
    public void saveHttpLog(Boolean isSuccess,String url,String content,String method,String header,String params,String response,String error,String type)
    {
        try {
            //成功日志是否保存
            Boolean saveSuccessLog = systemDictService.getSaveSuccessLog();
            if(!isSuccess || saveSuccessLog) {
                //新增日志
                PayLog log = new PayLog();
                log.setType(type);
                log.setApi(url);
                log.setContent(content);
                log.setMethod(method);
                log.setHeader(header);
                log.setParams(params);
                log.setCreateTime(new Date());
                log.setResponse(response);
                log.setError(error);
                log.setStatus(isSuccess?"1":"0");
                payLogDao.save(log);
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

+ 0 - 129
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java

@ -1,129 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.common;
import org.springframework.context.annotation.Configuration;
/**
 * User: hzp
 * Date: 20170518
 * 这里放置各种配置数据
 */
@Configuration
public class Configure {
	/******************************* 易联众统一支付平台 ***********************************************************/
//	private String onepayApi = "http://120.42.37.94:1301/onepay-web/";
//	private String onepayAppId = "1BGKM1UHM03P7B2CA8C000005626EB0E";
//	private String onepayAppSecret = "1BGKM1UHM03I7B2CA8C00000AB682E9A";
//			开发环境应用信息
//	private String onepayApi = "https://xmhealth.ylzpay.com:8080/";
	private String onepayApi = "http://xmhealth.ylzpay.com:8070/";
	private String onepayAppId = "1BLF5SEGN00087165F0A000027362BE5";
	private String onepayAppSecret = "1BLF5SCBO01V3E78A8C00000F3A0FFE7";
	private String bindCardType = "onepay.sicard.bind.info";
	private String chargeType = "onepay.trade.medical.charge";
	private String chargeQueryType = "onepay.trade.medical.charge.query";
	private String createSicardType = "onepay.sicard.createurl";
//	易联众异步回调
	private String receiveNotify = "wlyy.onepay.receiveNotify";
	private String returnUrl = "wlyy.onepay.returnUrl";
//  长处方系列
	private String recipeChargeType = "onepay.trade.long.recipe.charge";
	private String recipeReturnUrl = "wlyy.patient.prescription.pay.recipeReturnUrl";
	private String receiveRecipeNotify = "wlyy.patient.prescription.pay.receiveRecipeNotify";
	public String getRecipeChargeType() {
		return recipeChargeType;
	}
	public void setRecipeChargeType(String recipeChargeType) {
		this.recipeChargeType = recipeChargeType;
	}
	public String getRecipeReturnUrl() {
		return recipeReturnUrl;
	}
	public void setRecipeReturnUrl(String recipeReturnUrl) {
		this.recipeReturnUrl = recipeReturnUrl;
	}
	public String getReceiveRecipeNotify() {
		return receiveRecipeNotify;
	}
	public void setReceiveRecipeNotify(String receiveRecipeNotify) {
		this.receiveRecipeNotify = receiveRecipeNotify;
	}
	public String getReturnUrl() {
		return returnUrl;
	}
	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
	public String getReceiveNotify() {
		return receiveNotify;
	}
	public void setReceiveNotify(String receiveNotify) {
		this.receiveNotify = receiveNotify;
	}
	public String getOnepayApi() {
		return onepayApi;
	}
	public String getOnepayAppId() {
		return onepayAppId;
	}
	public String getOnepayAppSecret() {
		return onepayAppSecret;
	}
	public String getBindCardType() {
		return bindCardType;
	}
	public String getChargeType() {
		return chargeType;
	}
	public String getChargeQueryType() {
		return chargeQueryType;
	}
	public String getCreateSicardType() {
		return createSicardType;
	}
	/******************* 微信社保支付配置 ******************************************/
	//这个就是自己要保管好的私有Key了(切记只能放在自己的后台代码里,不能放在任何可能被看到源代码的客户端程序中)
	// 每次自己Post数据给API的时候都要用这个key来对所有字段进行签名,生成的签名会放在Sign这个字段,API收到Post数据的时候也会用同样的签名算法对Post过来的数据进行签名和验证
	// 收到API的返回的时候也要用这个key来对返回的数据算下签名,跟API的Sign数据进行比较,如果值不一致,有可能数据被第三方给篡改
	private String key = "2935b54b53a957d9516c920a544f2537";
	//微信分配的公众号ID(开通公众号之后可以获取到)
	private String appID = "wxd03f859efdf0873d";
	public String getKey(){
		return key;
	}
	public String getAppid(){
		return appID;
	}
	//获取token地址
	public String TOKEN_API = "https://api.weixin.qq.com/payinsurance/gettoken";
	//挂号/诊间支付统一下单 API 接口
	public String ORDER_API = "https://api.weixin.qq.com/payinsurance/unifiedorder?access_token ACCESS_TOKEN";
}

+ 17 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/quota/JobController.java

@ -451,6 +451,23 @@ public class JobController extends BaseController {
        }
    }
    /**
     * 遍历长处方支付但回调都失败的记录,主动查询易联众支付记录并保存
     *
     * @author wujunjie
     * @date 2017/8/30 14:16
     */
    @RequestMapping(value = "/prescriptionPayQueryJob", method = RequestMethod.POST)
    @ApiOperation("遍历长处方支付但回调都失败的记录,主动查询易联众支付记录并保存")
    public String PrescriptionPayQueryJob() {
        try {
            quartzHelper.startNow(PrescriptionPayQueryJob.class, "PRESCRIPTION-PAY_QUERY", null);
            return write(200, "启动成功");
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    //******************************长处方 end********************************
    /**
     * 居民监测方案提醒通知

+ 3 - 0
patient-co/patient-co-wlyy-job/src/main/resources/system.properties

@ -104,6 +104,9 @@ patient_disease_contion_syn_job=0 0 2 * * ?
#查询家庭签约支付结果,补更新医保签约号,3分钟跑一次
sign_family_pay_result_migisterno_job=0 0/3 * * * ?
# 家庭签约支付回调失败,每3分钟一次去主动查询并保存
onepay_query_job=0 0/3 * * * ?
#统一支付平台支付成功后页面跳转地址
return_url={server}/wx/html/qygl/html/pay_result.html

+ 1 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/adapter/PresModeAdapter.java

@ -308,6 +308,7 @@ public class PresModeAdapter {
                    prescriptionInfo.put("physicInjectPlaceName",info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                    prescriptionInfo.put("physicSkinTest",info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                    prescriptionInfo.put("physicSkinTestName",info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                    prescriptionInfo.put("subjectClass",info.getString("SUBJECT_CLASS"));//科目类型
                    prescriptionInfos.add(prescriptionInfo);
                }
                p.put("prescriptionInfo",prescriptionInfos);

+ 10 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PrenatalInspectorPlanDao.java

@ -1,7 +1,7 @@
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
@ -12,9 +12,16 @@ import java.util.List;
 */
public interface PrenatalInspectorPlanDao extends PagingAndSortingRepository<PrenatalInspectorPlan, Long>{
    @Query("select a from PrenatalInspectorPlan a where a.inspectionCode = ?1 and a.status = '0' order by a.inspectionStartTime asc")
    @Query("select a from PrenatalInspectorPlan a where a.inspectionCode = ?1 and a.status = '0' and a.del='1' order by a.inspectionTime asc")
    List<PrenatalInspectorPlan> findByCode(String inspectionCode);
    @Query("select a from PrenatalInspectorPlan a where a.inspectionTime is not null and a.status = '0' and ( TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=7 or TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=1 ) ")
    @Query("select a from PrenatalInspectorPlan a where a.patient = ?1 and a.status = '0' and a.del='1' and NOW()<=a.inspectionTime order by a.inspectionTime asc")
    List<PrenatalInspectorPlan> findByPatient(String patient);
    @Query("select a from PrenatalInspectorPlan a where a.status = '0' and a.del='1' and ( TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=7 or TO_DAYS(a.inspectionTime)- TO_DAYS(NOW())=1 ) ")
    List<PrenatalInspectorPlan> findWxTipList();
    @Modifying
    @Query("update PrenatalInspectorPlan a set a.del = '0' where a.patient= ?1 and a.del='1'")
    int updateStatus(String patient);
}

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

@ -14,7 +14,7 @@ import java.util.List;
public interface PrenatalInspectorPlanLibraryDao extends PagingAndSortingRepository<PrenatalInspectorPlanLibrary, Long>{
    @Query("select a from PrenatalInspectorPlanLibrary a where a.endDay >= ?1 order by a.endDay asc ")
    @Query("select a from PrenatalInspectorPlanLibrary a where a.endDay <= ?1 order by a.endDay desc ")
    List<PrenatalInspectorPlanLibrary> findByDays(Long endDay);
}

+ 11 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/zydict/ZyZoneDictDao.java

@ -0,0 +1,11 @@
package com.yihu.wlyy.repository.zydict;
import com.yihu.wlyy.entity.zydict.ZyZoneDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by yeshijie on 2017/10/10.
 */
public interface ZyZoneDictDao extends PagingAndSortingRepository<ZyZoneDict, Long>, JpaSpecificationExecutor<ZyZoneDict> {
}

+ 179 - 117
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java

@ -73,13 +73,7 @@ public class PrenatalInspectorPreCardService extends BaseService {
            json.put("name",plan.getName());
            json.put("thisFoucs",plan.getThisFocus());
            json.put("thisNote",plan.getThisNote());
            if(plan.getInspectionTime()==null){
                json.put("inspectionTime","");
            }else {
                json.put("inspectionTime",DateUtil.dateToStrShort(plan.getInspectionTime()));
            }
            json.put("inspectionEndTime",DateUtil.dateToStrShort(plan.getInspectionEndTime()));
            json.put("inspectionStartTime",DateUtil.dateToStrShort(plan.getInspectionStartTime()));
            json.put("inspectionTime",DateUtil.dateToStrShort(plan.getInspectionTime()));
            jsonArray.add(json);
        }
@ -107,7 +101,7 @@ public class PrenatalInspectorPreCardService extends BaseService {
            if(json.getInteger("status")==200){
                data = json.getJSONObject("data").getJSONArray("DATA");
            }
            if(data!=null&&data.size()>0){
            if(data!=null&&data.size()>0){//有建卡信息
                for (int i=0;i<data.size();i++) {
                    JSONObject planJson = new JSONObject();
                    JSONObject pregnancy = data.getJSONObject(i);
@ -126,45 +120,41 @@ public class PrenatalInspectorPreCardService extends BaseService {
                    planJson.put("expectedTime",EXPECTED_TIME);
                    Date date = new Date();
                    if(StringUtils.isBlank(END_TIME)){
                        //未结束妊娠,生成待产检计划
                        List<PrenatalInspectorPlan> plans = prenatalInspectorPlanDao.findByCode(PREGNANCY_NO);
                        if(plans==null||plans.size()==0){//判断是否已经生成产检记录
                            //获取最后一次检查时间-查询复检记录
                            String lastExamTime = getLastExamTime(patient.getIdcard(),hospital,PREGNANCY_NO);
                            if(StringUtils.isBlank(lastExamTime)){
                                lastExamTime = EXAM_TIME;
                        List<PrenatalInspectorPlan> plans = prenatalInspectorPlanDao.findByPatient(patientCode);
                        boolean flag = false;
                        if(plans==null||plans.size()==0){
                            flag = true;
                        }else {
                            String inspectionCode = plans.get(0).getInspectionCode();
                            if(StringUtils.isBlank(inspectionCode)){//有待产检计划,但是产检号为空,说明是预建卡生成的产检记录
                                flag = true;
                                //更新居民待产检计划,需要重新生成
                                prenatalInspectorPlanDao.updateStatus(patientCode);
                            }
                        }
                            Date lastMenstrualDate = DateUtil.strToDate(MENSES_LAST);
                            Long days = DateUtil.getDays(date,lastMenstrualDate);
                            days = days>365?0:days;//老早前的测试数据处理
                        if(flag){//判断是否已经生成产检记录
                            Date dueDay = DateUtil.strToDate(EXPECTED_TIME);
                            Long days = DateUtil.getDays(dueDay,date);
                            List<PrenatalInspectorPlanLibrary> libraries = prenatalInspectorPlanLibraryDao.findByDays(days);
                            plans = new ArrayList<>();
                            PrenatalInspectorPlan plan = null;
                            for (PrenatalInspectorPlanLibrary library:libraries){
                                Date startTime = DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getStartDay().intValue());
                                Long temp = DateUtil.getDays(DateUtil.strToDateLong(lastExamTime),startTime);
                                if(temp>0){//说明已经产检
                                    continue;
                                }
                                plan = new PrenatalInspectorPlan();
                                plan.setInspectionPhase(library.getInspectionPhase());
                                plan.setStatus("0");
                                plan.setPatient(patientCode);
                                plan.setCzrq(date);
                                plan.setCheckItem(library.getCheckItem());
                                plan.setDel("1");
                                plan.setInspectionCode(PREGNANCY_NO);//产检号
                                plan.setInspectionEndTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getEndDay().intValue()));
                                plan.setInspectionStartTime(startTime);
                                plan.setCheckItem(library.getCheckItem());
                                plan.setInspectionTime(DateUtil.getPrenatalInspectorDate(dueDay,-library.getEndDay().intValue()));
                                plan.setName(library.getName());
                                plan.setThisFocus(library.getThisFocus());
                                plan.setThisNote(library.getThisNote());
                                if("1".equals(plan.getInspectionPhase())&&signFamily!=null){
                                    plan.setSignHospital(signFamily.getHospital());
                                }
                                plans.add(plan);
                            }
                            if (plans.size()>0){
@ -202,8 +192,76 @@ public class PrenatalInspectorPreCardService extends BaseService {
                    }
                    re.add(planJson);
                }
            }
            }else{
                //没有建卡信息,请求预建卡接口
                response = jwMaternalChildService.getEhrMaternalPreFirstExamRecord(patient.getIdcard(),hospital);
                JSONObject preJson = JSONObject.parseObject(response);
                JSONArray preData = null;
                if(preJson.getInteger("status")==200){
                    preData = preJson.getJSONObject("data").getJSONArray("DATA");
                    if(preData!=null&&preData.size()>0){
                        for (int i=0;i<preData.size();i++){
                            JSONObject planJson = new JSONObject();
                            JSONObject pregnancy = preData.getJSONObject(i);
                            String PREGNANCY_NO = pregnancy.getString("PREGNANCY_NO");//智业产检号
                            String END_MANNER = pregnancy.getString("END_MANNER");//妊娠终止方式
                            String END_TIME = pregnancy.getString("END_TIME");//结束妊娠
                            String MENSES_LAST = pregnancy.getString("MENSES_LAST");//末次月经
                            Date dueday = DateUtil.getDueDate(DateUtil.strToDateLong(MENSES_LAST));//预产期
                            planJson.put("pregnancyNo",PREGNANCY_NO);
                            planJson.put("endManner",END_MANNER);
                            planJson.put("endTime",END_TIME);
                            planJson.put("mensesLast",MENSES_LAST);
                            planJson.put("expectedTime",DateUtil.dateToStrLong(dueday));
                            Date date = new Date();
                            List<PrenatalInspectorPlan> plans = prenatalInspectorPlanDao.findByPatient(patientCode);
                            if(plans==null||plans.size()==0){//判断是否已经生成产检记录
                                //预建卡还没产检,有产检就会生成产检记录,建卡接口就会有数据
                                Long days = DateUtil.getDays(dueday,date);
//                                days = days>365?0:days;//老早前的测试数据处理
                                List<PrenatalInspectorPlanLibrary> libraries = prenatalInspectorPlanLibraryDao.findByDays(days);
                                plans = new ArrayList<>();
                                PrenatalInspectorPlan plan = null;
                                for (PrenatalInspectorPlanLibrary library:libraries){
                                    plan = new PrenatalInspectorPlan();
                                    plan.setInspectionPhase(library.getInspectionPhase());
                                    plan.setStatus("0");
                                    plan.setPatient(patientCode);
                                    plan.setCzrq(date);
                                    plan.setDel("1");
                                    plan.setCheckItem(library.getCheckItem());
//                                    plan.setInspectionCode(PREGNANCY_NO);//产检号
                                    plan.setInspectionTime(DateUtil.getPrenatalInspectorDate(dueday,-library.getEndDay().intValue()));
//                                    plan.setInspectionEndTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getEndDay().intValue()));
//                                    plan.setInspectionStartTime(DateUtil.getPrenatalInspectorDate(dueday,-library.getEndDay().intValue()));
                                    plan.setName(library.getName());
                                    plan.setThisFocus(library.getThisFocus());
                                    plan.setThisNote(library.getThisNote());
                                    plans.add(plan);
                                }
                                if (plans.size()>0){
                                    prenatalInspectorPlanDao.save(plans);
                                }
                            }
                            //计算距离下次产检时间
                            Long nextExamDay = 0l;
                            for (PrenatalInspectorPlan plan:plans) {
                                Long temp = DateUtil.getDays(date,plan.getInspectionStartTime());
                                if(nextExamDay==0||nextExamDay>temp){
                                    nextExamDay = temp;
                                }
                            }
                            planJson.put("plans",plans);//待产检列表
                            planJson.put("nextExamDay",nextExamDay);//距离下次产检天数
                            planJson.put("precontractOrgName",null);//产床医院
                            re.add(planJson);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
@ -236,6 +294,49 @@ public class PrenatalInspectorPreCardService extends BaseService {
                for (int i=0;i<data.size();i++){
                    if(pregnancyNo.equals(data.getJSONObject(i).getString("PREGNANCY_NO"))){//判断是否同一个产检
                        re = data.getJSONObject(i);
                        String SICK_PROVINCE = re.getString("SICK_PROVINCE");//省
                        String SICK_CITY = re.getString("SICK_CITY");//市
                        String SICK_COUNTY = re.getString("SICK_COUNTY");//县
                        String SICK_COUNTRY = re.getString("SICK_COUNTRY");//街道
                        String SICK_VILLAGE = re.getString("SICK_VILLAGE");//居委会
                        String SICK_HOUSEHOLD_PROVINCE = re.getString("SICK_HOUSEHOLD_PROVINCE");//户籍省
                        String SICK_HOUSEHOLD_CITY = re.getString("SICK_HOUSEHOLD_CITY");//户籍市
                        String SICK_HOUSEHOLD_COUNTY = re.getString("SICK_HOUSEHOLD_COUNTY");//户籍县
                        String SICK_HOUSEHOLD_COUNTRY = re.getString("SICK_HOUSEHOLD_COUNTRY");//户籍街道
                        String SICK_HOUSEHOLD_VILLAGE = re.getString("SICK_HOUSEHOLD_VILLAGE");//户籍居委会
                        if(StringUtils.isNotBlank(SICK_PROVINCE)){
                            re.put("SICK_PROVINCE",zyDictService.findZoneName(SICK_PROVINCE));
                        }
                        if(StringUtils.isNotBlank(SICK_CITY)){
                            re.put("SICK_CITY",zyDictService.findZoneName(SICK_CITY));
                        }
                        if(StringUtils.isNotBlank(SICK_COUNTY)){
                            re.put("SICK_COUNTY",zyDictService.findZoneName(SICK_COUNTY));
                        }
                        if(StringUtils.isNotBlank(SICK_COUNTRY)){
                            re.put("SICK_COUNTRY",zyDictService.findZoneName(SICK_COUNTRY));
                        }
                        if(StringUtils.isNotBlank(SICK_VILLAGE)){
                            re.put("SICK_VILLAGE",zyDictService.findZoneName(SICK_VILLAGE));
                        }
                        if(StringUtils.isNotBlank(SICK_HOUSEHOLD_PROVINCE)){
                            re.put("SICK_HOUSEHOLD_PROVINCE",zyDictService.findZoneName(SICK_HOUSEHOLD_PROVINCE));
                        }
                        if(StringUtils.isNotBlank(SICK_HOUSEHOLD_CITY)){
                            re.put("SICK_HOUSEHOLD_CITY",zyDictService.findZoneName(SICK_HOUSEHOLD_CITY));
                        }
                        if(StringUtils.isNotBlank(SICK_HOUSEHOLD_COUNTY)){
                            re.put("SICK_HOUSEHOLD_COUNTY",zyDictService.findZoneName(SICK_HOUSEHOLD_COUNTY));
                        }
                        if(StringUtils.isNotBlank(SICK_HOUSEHOLD_COUNTRY)){
                            re.put("SICK_HOUSEHOLD_COUNTRY",zyDictService.findZoneName(SICK_HOUSEHOLD_COUNTRY));
                        }
                        if(StringUtils.isNotBlank(SICK_HOUSEHOLD_VILLAGE)){
                            re.put("SICK_HOUSEHOLD_VILLAGE",zyDictService.findZoneName(SICK_HOUSEHOLD_VILLAGE));
                        }
                        return re;
                    }
                }
@ -286,7 +387,7 @@ public class PrenatalInspectorPreCardService extends BaseService {
            }
            if(data!=null&&data.size()>0){
                JSONObject exam = data.getJSONObject(data.size()-1);
                String PREGNANCY_WEEK = exam.getString("PREGNANCY_WEEK");//检查孕周
//                String PREGNANCY_WEEK = exam.getString("PREGNANCY_WEEK");//检查孕周
                String examTime = exam.getString("EXAM_TIME");//产检日期
                re = examTime;
            }
@ -382,13 +483,30 @@ public class PrenatalInspectorPreCardService extends BaseService {
     * 上传预建卡
     * @param code
     */
    public void uploadPreExam(String code){
    public String uploadPreExam(String code){
        String re = "";
        try {
            //上传预建卡
            jwMaternalChildService.SaveEhrMaternalPreFirstExamRecord(code);
            String response = jwMaternalChildService.SaveEhrMaternalPreFirstExamRecord(code);
            JSONObject preJson = JSONObject.parseObject(response);
            if(preJson.getInteger("status")!=200){
                re = preJson.getString("msg");
            }else {
                JSONObject json = preJson.getJSONObject("data");
                if("0".equals(json.getString("code"))){
                    re = json.getString("MESSAGE");
                }
            }
            if(re.contains("身份证为空,请检查")){
                re = "身份证为空,请检查";
            }else if(re.contains("操作员为空,请检查")){
                re = "操作员为空,请检查";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return re;
    }
    /**
@ -415,115 +533,59 @@ public class PrenatalInspectorPreCardService extends BaseService {
        String re = "";
        //1、保存预建卡
        Date date = new Date();
//        Date lastMenstrualDate = preCard.getLastMenstrualDate();
        Date lastMenstrualDate = preCard.getLastMenstrualDate();
        Date dueDate = DateUtil.getDueDate(preCard.getLastMenstrualDate());
        preCard.setDel("1");
        preCard.setCode(getCode());
        preCard.setCzrq(date);
        preCard.setDueDate(DateUtil.getDueDate(preCard.getLastMenstrualDate()));//预产期
        preCard.setDueDate(dueDate);//预产期
        preCard.setStatus("0");
        preCard.setEffective("");
        preCard.setInspectionPhase("1");//检查阶段
        preCard.setUploadStatus("0");//未上传
        prenatalInspectorPreCardDao.save(preCard);
//        String patient = preCard.getPatient();
        String patient = preCard.getPatient();
        //2.更新居民信息
        //更新居民信息
//        Patient p = patientDao.findByCode(patient);
//        p.setName(preCard.getName());
//        p.setSsc(preCard.getSsc());
//        p.setBirthday(preCard.getBirthday());
//        p.setMobile(preCard.getMobile());
        return preCard.getCode();
        //2、生成待产检计划(待产检计划由获取健康信息接口生成,关联产检计划)
//        Long days = DateUtil.getDays(date,lastMenstrualDate);
//        List<PrenatalInspectorPlanLibrary> libraries = prenatalInspectorPlanLibraryDao.findByDays(days);
//        List<PrenatalInspectorPlan> plans = new ArrayList<>();
//        PrenatalInspectorPlan plan = null;
//        for (PrenatalInspectorPlanLibrary library:libraries){
//            plan = new PrenatalInspectorPlan();
//            plan.setInspectionPhase(library.getInspectionPhase());
//            plan.setStatus("0");
//            plan.setPatient(patient);
//            plan.setCzrq(date);
//            plan.setCheckItem(library.getCheckItem());
        Long days = DateUtil.getDays(dueDate,date);
        List<PrenatalInspectorPlanLibrary> libraries = prenatalInspectorPlanLibraryDao.findByDays(days);
        List<PrenatalInspectorPlan> plans = new ArrayList<>();
        PrenatalInspectorPlan plan = null;
        for (PrenatalInspectorPlanLibrary library:libraries){
            plan = new PrenatalInspectorPlan();
            plan.setInspectionPhase(library.getInspectionPhase());
            plan.setStatus("0");
            plan.setPatient(patient);
            plan.setCzrq(date);
            plan.setDel("1");
            plan.setCheckItem(library.getCheckItem());
//            plan.setInspectionCode(preCard.getCode());
//            plan.setInspectionEndTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getEndDay().intValue()));
//            plan.setInspectionStartTime(DateUtil.getPrenatalInspectorDate(lastMenstrualDate,library.getStartDay().intValue()));
//            plan.setName(library.getName());
//            plan.setThisFocus(library.getThisFocus());
//            plan.setThisNote(library.getThisNote());
//
            plan.setInspectionTime(DateUtil.getPrenatalInspectorDate(dueDate,-library.getEndDay().intValue()));
            plan.setName(library.getName());
            plan.setThisFocus(library.getThisFocus());
            plan.setThisNote(library.getThisNote());
//            if("1".equals(plan.getInspectionPhase())){
//                SignFamily jiating = familyContractService.findByPatientByType(patient, 2);
//                if(jiating!=null){
//                    plan.setSignHospital(jiating.getHospital());
//                }
//            }
//
//            plans.add(plan);
//        }
//        if (plans.size()>0){
//            prenatalInspectorPlanDao.save(plans);
//        }
    }
    /**
     * 产检提醒(1预约提醒,2就诊提醒)
     * 1、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前7天(保证居民可自行预约),发出产检预约提醒通知。点击该消息,进入预约页面
     * 2、当居民已有经医生确认过的下一次产检时间,则距离下一次产检前1天,发出产检就诊提醒,提醒居民就诊。点击该消息,进入预约记录页面
     */
    public void sendPrenatalInspectorRemind(){
        System.out.println("产检计划---running");
        List<PrenatalInspectorPlan> planList = prenatalInspectorPlanDao.findWxTipList();
        for (PrenatalInspectorPlan plan:planList){
            try {
                Patient patient = patientDao.findByCode(plan.getPatient());
                String openId = patient.getOpenid();
                String name = patient.getName();
                String patientCode = patient.getCode();
                if(StringUtils.isNotBlank(openId)){
                    Long day = DateUtil.getDays(plan.getInspectionTime(),DateUtil.getNowDateShort());
                    org.json.JSONObject json = new org.json.JSONObject();
                    if(day==7){
                        //产检提醒
                        json.put("remark","产检内容以医生实际检查为准。点击进行预约");
                        json.put("first",name+",您好!您和您的宝宝需要进行产检啦~请及时预约产检,如已预约,请忽略");
                        if("1".equals(plan.getInspectionPhase())){
                            if(StringUtils.isNotBlank(plan.getSignHospital())){
                                json.put("url","wdyy/html/hospital-dept.html?openid="+openId+"&toUser="+patientCode+"&toName="+name+"&hospitalId="+plan.getSignHospital());
                            }else {
                                json.put("url","wdyy/html/appointment-register.html?openid="+openId+"&toUser="+patientCode+"&toName="+name+"&orderType=1");
                            }
                        }else {
                            json.put("url","wdyy/html/appointment-register.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
                        }
                        json.put("keyword1","产检提醒");
                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
                        json.put("keyword2",keyword2);
                        pushMsgTask.sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
                    }else if(day==1){
                        //产检就诊提醒
                        json.put("remark","产检内容以医生实际检查为准。点击查看预约记录");
                        json.put("first",name+",您好!您和您的宝宝即将进行产检啦~请按时就诊,如已就诊,请忽略");
                        json.put("url","wdyy/html/my-appointment.html?openid="+openId+"&toUser="+patientCode+"&toName="+name);
                        json.put("keyword1","产检就诊提醒");
                        String keyword2 = DateUtil.getStringDateShort()+"\n产检内容:"+plan.getCheckItem();
                        json.put("keyword2",keyword2);
                        pushMsgTask.sendWeixinMessage(accessTokenUtils.getAccessToken(), 18, openId, name, json);
                    }
                }
            }catch (Exception e){
                System.out.println("微信提醒发送失败");
                e.printStackTrace();
            }
            plans.add(plan);
        }
        if (plans.size()>0){
            prenatalInspectorPlanDao.save(plans);
        }
        return preCard.getCode();
    }
}

File diff suppressed because it is too large
+ 266 - 210
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PatientPrescriptionPayService.java


+ 72 - 8
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsService.java

@ -4158,34 +4158,65 @@ public class StatisticsService extends BaseService {
        return results;
    }
    public JSONObject getRenewPercentAndChangePercent(String renewIndex, String level, String code, String year) {
    public JSONObject getRenewPercentAndChangePercent(String renewIndex, String level, String code, String year, String lowCode) {
        String switchIndex = "";
        if ("2".equals(level)) {
            //团队的转签
            switchIndex = "35";
            if(StringUtils.isNoneBlank(lowCode)){
                //服务类型维度
                switchIndex = "55";
            }else{
                switchIndex = "35";
            }
        } else if ("3".equals(level)) {
            //社区的转签
            switchIndex = "35";
            if(StringUtils.isNoneBlank(lowCode)){
                //服务类型维度
                switchIndex = "56";
            }else{
                switchIndex = "35";
            }
        } else {
            //区和市的转签
            switchIndex = "35";
            if(StringUtils.isNoneBlank(lowCode)){
                //服务类型维度
                switchIndex = "57";
            }else{
                switchIndex = "35";
            }
        }
        JSONObject jo = new JSONObject();
        
        String rediscode = code;
        
        //如果服务类型维度code(老年人3,高血压4,糖尿病5)不为空,则rediscode默认带上lowcode
        if(StringUtils.isNoneBlank(lowCode)){
            rediscode = rediscode + ":"+lowCode;
        }
        
        //获取时间戳
        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
        int renewNum = getLevel1NumForRedis(renewIndex, level, code, timeKey);
        int renewNum = getLevel1NumForRedis(renewIndex, level, rediscode, timeKey);
        //根据年度获取去年的签约数 签约指标是1
        String date = year + "-06-30";
        String index = "1";
        WlyyQuotaResult wlyyQuotaResult = findOneQuotaResult(date, Integer.valueOf(level), index, code);
        
        int signNum = 0;
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
    
        if(StringUtils.isNoneBlank(lowCode)){
            wlyyQuotaResult = findOneQuotaResultWithLevelType2(date, Integer.valueOf(level), index, code,lowCode);
        }else{
            wlyyQuotaResult = findOneQuotaResult(date, Integer.valueOf(level), index, code);
        }
        
        if (wlyyQuotaResult != null) {
            signNum = Integer.valueOf(wlyyQuotaResult.getResult());
        }
        //从redis中获取最新的转签数据  指标是37
        int switchNum = getLevel1NumForRedis(switchIndex, level, code, timeKey);
        int switchNum = getLevel1NumForRedis(switchIndex, level, rediscode, timeKey);
        jo.put("yesterYearSign", signNum);//去年的签约量
        jo.put("thisYearRenew", renewNum);//今年的续签量
        jo.put("thisYearSwithch", switchNum);//今年的转签量
@ -4195,7 +4226,8 @@ public class StatisticsService extends BaseService {
        return jo;
    }
    
    
    public JSONObject getRenewAnalysis(String switchIndex, String switchIndexReson, String signIn, String signOut, String level, String code) {
        JSONObject jo = new JSONObject();
@ -4790,5 +4822,37 @@ public class StatisticsService extends BaseService {
            return null;
        }
    }
    
    /**
     * 获取单个数据(二级维度)
     *
     * @param date
     * @param level
     * @param index
     * @param area
     * @param lowCode
     * @return
     */
    private WlyyQuotaResult findOneQuotaResultWithLevelType2(String date, int level, String index, String area,String lowCode) {
        String sql = " select * from wlyy_quota_result w where w.quota_date ='" + date + "' and w.quato_code='" + index + "' and w.level1_type= '" + level + "' and w.level2_type = "+lowCode;
        if (level == 4) {
            // 市级别
            sql += " and city='" + area + "' ";
        } else if (level == 3) {
            // 区、城镇级别
            sql += " and town='" + area + "' ";
        } else if (level == 2) {
            // 机构级别
            sql += " and org_code='" + area + "' ";
        } else if (level == 1) {
            // 机构级别
            sql += " and qkdoctor_code ='" + area + "'";
        }
        List<WlyyQuotaResult> results = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyQuotaResult.class));
        if (results.size() > 0) {
            return results.get(0);
        }
        return null;
    }
}

+ 575 - 66
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java

@ -2,8 +2,11 @@ package com.yihu.wlyy.service.app.statisticsES;
import com.yihu.wlyy.config.es.ElasticFactory;
import com.yihu.wlyy.entity.patient.prescription.PrescriptionDispensaryCode;
import com.yihu.wlyy.entity.statistics.PopulationBase;
import com.yihu.wlyy.util.Constant;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ElasticsearchUtil;
import com.yihu.wlyy.util.IdcardInfoExtractor;
import com.yihu.wlyy.web.quota.vo.SaveModel;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
@ -13,13 +16,13 @@ import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.*;
/**
 * Created by ${liuwenbin} on 2017/9/14.
@ -31,6 +34,8 @@ public class StatisticsESService {
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 获取上次统计时间
@ -69,104 +74,354 @@ public class StatisticsESService {
    }
    /**
     * 获取时间范围内按间隔统计指标增量
     * 获取所有指标的增量、到达量
     * 备注:原来接口的一级指标对应现在的
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @param interval  时间间隔
     * @param area      区域或机构代码
     * @param level     级别
     * @param index     指标
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    public JSONArray getDateIncrementDetail(String startDate, String endDate, int interval, String area, String level, String index, String level2_type) throws Exception {
        if (interval == 1) {
            return dateStatistics(startDate, endDate, area, level, index, level2_type);
        } else if (interval == 2) {
//            return weekStatistics(startDate, endDate, area, level, index, level2_type);
        } else if (interval == 3) {
//            return monthStatistics(startDate, endDate, area, level, index, level2_type);
    public List findOneDateQuotaLevel0(String startDate,String endDate, String area, int level, String index,String timeLevel,String interval,String lowLevel) throws Exception {
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        if (SaveModel.teamLevel.equals(level+"")) {
            sql.append("select team,teamName,sum(result1) result1, sum(result2) result2 from wlyy_quota_test where team='" + area + "'");
            groupBy.append("  group by team,teamName");
        } else if (SaveModel.OrgLevel.equals(level+"")) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where hospital='" + area + "'");
            groupBy.append("  group by hospital");
        } else if (SaveModel.townLevel.equals(level+"")) {
            sql.append("select town,townName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where town='" + area + "'");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(level+"")) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where city='" + area + "'");
            groupBy.append("  group by city,cityName");
        }
        sql.append(" and quotaCode='"+index+"'  ");
        sql.append(" and timeLevel='"+timeLevel+"'  ");
        sql.append(" and areaLevel='5'");
        if(StringUtils.isNotEmpty(startDate)){
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if(StringUtils.isNotEmpty(endDate)){
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if(StringUtils.isNotEmpty(lowLevel)){
        return new JSONArray();
            if (SaveModel.teamLevel.equals(lowLevel)) {
                sql.append(" and team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(lowLevel)) {
                sql.append(" and hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(lowLevel)) {
                sql.append(" and town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(lowLevel)) {
                sql.append(" and city='" + area + "'");
            }
        }
        //根据时间维度分组
        if(StringUtils.isNotEmpty(interval)){
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d') ");
            }
        }
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
    }
    /**
     * 按日统计
     * 获取一级指标的增量、到达量
     * 备注:原接口的二级指标对应现在的一级指标
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    private JSONArray dateStatistics(String startDate, String endDate, String area, String level, String index, String level2_type) {
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        // 起始日期
//        Calendar start = Calendar.getInstance();
//        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
//        //结束日期
//        Calendar end = Calendar.getInstance();
//        end.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        // 日期集合
//        List<Calendar> days = new ArrayList<>();
//        days.add(start);
//        boolean flag = true;
//        if (startDate.compareTo(endDate) == 0) {
//            flag = false;
//        }
//         计算统计日期
//        while (flag) {
//            Calendar next = Calendar.getInstance();
//            next.setTime(days.get(days.size() - 1).getTime());
//            next.add(Calendar.DATE, 1);
//            if (df.format(next.getTime()).compareTo(endDate) < 0) {
//                days.add(next);
//            } else {
//                days.add(end);
//                flag = false;
//            }
//        }
        startDate = changeDate(startDate);
        endDate = changeDate(endDate);
    public List findOneDateQuotaLevel1(String startDate,String endDate, String area, int level, String index,String timeLevel,String slaveKey1,String interval,String lowLevel ) throws Exception{
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        if (SaveModel.teamLevel.equals(level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,result1,result2 from wlyy_quota_test where team='" + area + "'");
        if (SaveModel.teamLevel.equals(level+"")) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2 from wlyy_quota_test where team='" + area + "'");
            groupBy.append("  group by team,teamName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.OrgLevel.equals(level)) {
        } else if (SaveModel.OrgLevel.equals(level+"")) {
            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where hospital='" + area + "'");
            groupBy.append("  group by hospital,hospitalName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.townLevel.equals(level)) {
        } else if (SaveModel.townLevel.equals(level+"")) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where town='" + area + "'");
            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.cityLevel.equals(level)) {
        } else if (SaveModel.cityLevel.equals(level+"")) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where city='" + area + "'");
            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name");
        }
        sql.append(" and quotaCode='"+index+"'  ");
        sql.append(" and timeLevel='"+timeLevel+"'  ");
        sql.append(" and areaLevel='5'");
        if(StringUtils.isNotEmpty(startDate)){
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if(StringUtils.isNotEmpty(endDate)){
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if(StringUtils.isNotEmpty(slaveKey1)){
            sql.append(" and slaveKey1='"+slaveKey1+"'  ");
        }
        if(StringUtils.isNotEmpty(lowLevel)){
            if (SaveModel.teamLevel.equals(lowLevel)) {
                sql.append(" and team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(lowLevel)) {
                sql.append(" and hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(lowLevel)) {
                sql.append(" and town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(lowLevel)) {
                sql.append(" and city='" + area + "'");
            }
        }
        //根据时间维度分组
        if(StringUtils.isNotEmpty(interval)){
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d') ");
            }
        }
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
    }
    /**
     * 获取二级指标的增量、到达量
     * 备注:原接口的三级指标对应现在的二级指标
     *
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    public List findOneDateQuotaLevel2(String startDate,String endDate, String area, int level, String index,String timeLevel,String slaveKey1,String slaveKey2,String interval,String lowLevel){
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        endDate = changeDate(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        if (SaveModel.teamLevel.equals(level+"")) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,result1,result2 from wlyy_quota_test where team='" + area + "'");
            groupBy.append("  group by team,teamName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name");
        } else if (SaveModel.OrgLevel.equals(level+"")) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where hospital='" + area + "'");
            groupBy.append("  group by hospital,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,hospitalName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name");
        } else if (SaveModel.townLevel.equals(level+"")) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where town='" + area + "'");
            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name");
        } else if (SaveModel.cityLevel.equals(level+"")) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where city='" + area + "'");
            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name");
        }
        sql.append(" and quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='1'  ");
        sql.append(" and areaLevel='"+level+"'");
        sql.append(" and quotaDate>='" + startDate + "'");
        sql.append(" and quotaDate<='" + endDate + "'");
        if(StringUtils.isNotBlank(level2_type)){
            sql.append(" and slaveKey2='"+level2_type+"'");
            groupBy.append(",slaveKey2,slaveKey2Name");
        sql.append(" and timeLevel='"+timeLevel+"'  ");
        sql.append(" and areaLevel='5'");
        if(StringUtils.isNotEmpty(startDate)){
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if(StringUtils.isNotEmpty(endDate)){
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if(StringUtils.isNotBlank(slaveKey1)){
            sql.append(" and slaveKey1='"+slaveKey1+"'");
        }
        if(StringUtils.isNotBlank(slaveKey2)){
            sql.append(" and slaveKey2='"+slaveKey2+"'");
        }
        if(StringUtils.isNotEmpty(lowLevel)){
            if (SaveModel.teamLevel.equals(lowLevel)) {
                sql.append(" and team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(lowLevel)) {
                sql.append(" and hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(lowLevel)) {
                sql.append(" and town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(lowLevel)) {
                sql.append(" and city='" + area + "'");
            }
        }
        //根据时间维度分组
        if(StringUtils.isNotEmpty(interval)){
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d') ");
            }
        }
        sql.append(groupBy);
        List<SaveModel> list =elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
        return elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
    }
//    /**
//     * 查询某一天父level下的子level 例如 查询市下面的团队,或者区下面的团队
//     *
//     * @param index      指标code
//     * @param area           机构code或者团队code或者town code或者city code
//     * @param timeLevel      1增量 2到达量
//     * @param level      父arealevel
//     * @param lowLevel 子arealevel
//     * @return
//     */
//    public List<SaveModel> findOneDateQuotaByChllevel(String startDate,
//                                                      String endDate,
//                                                      String index,
//                                                      String area,
//                                                      String timeLevel,
//                                                      String level,
//                                                      String lowLevel) {
//
//        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
//        startDate = changeDate(startDate);
//        endDate = changeDate(endDate);
//
//        StringBuffer sql = new StringBuffer();
//        StringBuffer groupBy = new StringBuffer();
//        //根据 childAreaLevel   group by
//        if (SaveModel.teamLevel.equals(level)) {
//            sql.append("select team,teamName,result1,result2 from wlyy_quota_test where  ");
//            groupBy.append(" group by team,teamName");
//        } else if (SaveModel.OrgLevel.equals(level)) {
//            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where  ");
//            groupBy.append(" group by hospital,hospitalName");
//        } else if (SaveModel.townLevel.equals(level)) {
//            sql.append("select town,townName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where ");
//            groupBy.append(" group by town,townName");
//        } else if (SaveModel.cityLevel.equals(level)) {
//            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where  ");
//            groupBy.append(" group by city,cityName");
//        }
//
//        sql.append("  quotaCode='" + index + "'  ");
//        sql.append(" and timeLevel='" + timeLevel + "'  ");
//        sql.append(" and areaLevel='5'");
//        if(StringUtils.isNotEmpty(startDate)){
//            sql.append(" and quotaDate>='" + startDate + "'");
//        }
//        if(StringUtils.isNotEmpty(endDate)){
//            sql.append(" and quotaDate<='" + endDate + "'");
//        }
//        //查询code
//        if (SaveModel.teamLevel.equals(lowLevel)) {
//            sql.append(" and team='" + area + "'");
//        } else if (SaveModel.OrgLevel.equals(lowLevel)) {
//            sql.append(" and hospital='" + area + "'");
//        } else if (SaveModel.townLevel.equals(lowLevel)) {
//            sql.append(" and town='" + area + "'");
//        } else if (SaveModel.cityLevel.equals(lowLevel)) {
//            sql.append(" and city='" + area + "'");
//        }
//        sql.append(groupBy);
//        return elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
//    }
    /**
     * 获取时间范围内按间隔统计指标增量
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @param interval  时间间隔
     * @param area      区域或机构代码
     * @param level     级别
     * @param index     指标
     * @return
     */
    public JSONArray getDateIncrementDetail(String startDate, String endDate, String interval, String area, int level, String index, String level2_type) throws Exception {
        List<SaveModel>  list = findOneDateQuotaLevel1(startDate,endDate,area,level,index,"1",level2_type,interval,null);
        List<JSONObject> result = new ArrayList<>();
        for (SaveModel saveModel:list){
            JSONObject range = new JSONObject();
            range.put("range", saveModel.getQuotaDate());
            range.put("amount", saveModel.getResult1());
            range.put("range", DateUtil.dateToStr(saveModel.getQuotaDate(),"yyyy-MM-dd HH:mm:ss"));
            range.put("amount", saveModel.getResult2());
            result.add(range);
        }
        return new JSONArray(result);
    }
//    /**
//     * 按日统计
//     *
//     * @param startDate
//     * @param endDate
//     * @param area
//     * @param level
//     * @param index
//     * @return
//     */
//    private JSONArray dateStatistics(String startDate, String endDate, String area, int level, String index, String level2_type,String interval) {
//
//        startDate = changeDate(startDate);
//        endDate = changeDate(endDate);
//        StringBuffer sql = new StringBuffer();
//        StringBuffer groupBy = new StringBuffer();
//        if (SaveModel.teamLevel.equals(level+"")) {
//            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2 from wlyy_quota_test where team='" + area + "'");
//            groupBy.append("  group by team,teamName,slaveKey1,slaveKey1Name");
//        } else if (SaveModel.OrgLevel.equals(level+"")) {
//            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where hospital='" + area + "'");
//            groupBy.append("  group by hospital,hospitalName,slaveKey1,slaveKey1Name");
//        } else if (SaveModel.townLevel.equals(level+"")) {
//            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where town='" + area + "'");
//            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name");
//        } else if (SaveModel.cityLevel.equals(level+"")) {
//            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from wlyy_quota_test where city='" + area + "'");
//            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name");
//        }
//        sql.append(" and quotaCode='" + index + "'  ");
//        sql.append(" and timeLevel='1'  ");
//        sql.append(" and areaLevel='5'");
//        sql.append(" and quotaDate>='" + startDate + "'");
//        sql.append(" and quotaDate<='" + endDate + "'");
//        if(StringUtils.isNotBlank(level2_type)){
//            sql.append(" and slaveKey2='"+level2_type+"'");
//            groupBy.append(",slaveKey2,slaveKey2Name");
//        }
//        //根据时间维度分组
//        if (SaveModel.interval_month.equals(interval)) {
//            groupBy.append(" ,date_histogram(field='quotaDate','interval'='month') ");
//        } else if (SaveModel.interval_week.equals(interval)) {
//            groupBy.append(" ,date_histogram(field='quotaDate','interval'='week') ");
//        } else if (SaveModel.interval_day.equals(interval)) {
//            groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d') ");
//        }
//        sql.append(groupBy);
//        List<SaveModel> list =elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
//        List<JSONObject> result = new ArrayList<>();
//        for (SaveModel saveModel:list){
//            JSONObject range = new JSONObject();
//            range.put("range", DateUtil.dateToStr(saveModel.getQuotaDate(),"yyyy-MM-dd HH:mm:ss"));
//            range.put("amount", saveModel.getResult2());
//            result.add(range);
//        }
//        return new JSONArray(result);
//    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
@ -177,4 +432,258 @@ public class StatisticsESService {
        return quotaDate + "T00:00:00+0800";
    }
    /**
     * 查询截止某个日期累计量
     *
     * @param endDate     截止日期
     * @param area        区域或机构代码
     * @param level       级别
     * @param level2_type level2_type的类型
     * @return
     */
    public long getTotalAmount(String startDate, String endDate, String area, int level, String index, String level2_type)  throws Exception {
        startDate = changeDate(startDate);
        endDate = changeDate(endDate);
        List<SaveModel>  list = findOneDateQuotaLevel1(startDate,endDate,area,level,index,"1",level2_type,null,null);
        if(list.size()>0){
            return list.get(0).getResult2();
        }
        return 0L;
    }
    /**
     * 查询截止某个日期某个区域后机构各下级指标累计情况
     *
     * @param endDate 截止日期
     * @param area    区域或机构代码
     * @param level   级别
     * @return
     */
    public JSONArray getLowLevelTotalDetail(String endDate, String area, int level, String index, int sort, String lowLevel, String level2_type, String year) throws Exception {
        String startDate = "";
        //如果year有值 就按照年度来查询 即2017年 就是大于2017-06-30
        if (!org.springframework.util.StringUtils.isEmpty(year)) {
            startDate = year + "-06-30' ";
        }
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if(StringUtils.isNotEmpty(startDate)){
            startDate = changeDate(startDate);
        }
        endDate = changeDate(endDate);
        String levelTemp = level+"";
        if(StringUtils.isNotEmpty(lowLevel)){
            levelTemp = lowLevel;
        }
        List<SaveModel>  list = findOneDateQuotaLevel1(startDate,endDate,area,level,index,"1",level2_type,null,lowLevel);
        if (org.springframework.util.StringUtils.isEmpty(year)) {
            year = Constant.getNowYear();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        PopulationBase populationBase = getPopulationBase(area,year);
        DecimalFormat df = new DecimalFormat("0.0000");
        for (SaveModel saveModel:list) {
            Map<String, Object> map = new HashMap<>();
            if (SaveModel.OrgLevel.equals(levelTemp)) {
                map.put("code",saveModel.getHospital());
                map.put("name",saveModel.getHospitalName());
            } else if (SaveModel.townLevel.equals(levelTemp)) {
                map.put("code",saveModel.getTown());
                map.put("name",saveModel.getTownName());
            } else if (SaveModel.cityLevel.equals(levelTemp)) {
                map.put("code",saveModel.getCity());
                map.put("name",saveModel.getCityName());
            } else if (SaveModel.teamLevel.equals(level+"")) {
                map.put("code",saveModel.getTeam());
                map.put("name",saveModel.getCityName());
            }
            map.put("amount",saveModel.getResult2());
            map.put("rate",df.format((saveModel.getResult2() * 1.0000) / populationBase.getNum() * 100));
            map.put("rateString",saveModel.getResult2()+"/"+populationBase.getNum());
            resultList.add(map);
        }
        Collections.sort(resultList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int map1value = (int) o1.get("amount");
                int map2value = (int) o2.get("amount");
                if (map1value - map2value > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value - map2value < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        return new JSONArray(resultList);
    }
    public JSONArray getIndexLevelTwototal(String endDate, String area, int level, String index) throws Exception{
//        List<SaveModel> list =findOneDateQuotaLevel2(endDate, area, level, index,"1","");
        List<SaveModel> list = findOneDateQuotaLevel1(endDate,endDate,area,level,index,"1",null,null,null);
        List<Map<String, Object>> resultList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.0000");
        long total = 0;
        for (SaveModel saveModel:list) {
            Map<String, Object> map = new HashMap<>();
            if (SaveModel.OrgLevel.equals(level+"")) {
                map.put("code",saveModel.getHospital());
                map.put("name",saveModel.getHospitalName());
            } else if (SaveModel.townLevel.equals(level+"")) {
                map.put("code",saveModel.getTown());
                map.put("name",saveModel.getTownName());
            } else if (SaveModel.cityLevel.equals(level+"")) {
                map.put("code",saveModel.getCity());
                map.put("name",saveModel.getCityName());
            } else if (SaveModel.teamLevel.equals(level+"")) {
                map.put("code",saveModel.getTeam());
                map.put("name",saveModel.getCityName());
            }
//            map.put("amount",saveModel.getResult2());
//            map.put("rate",df.format((saveModel.getResult2() * 1.0000) / populationBase.getNum() * 100));
//            map.put("rateString",saveModel.getResult2()+"/"+populationBase.getNum());
            map.put("amount", saveModel.getResult2());
            if (index.equals("7")) {
                // 分组指标总数算法
                String code = saveModel.getSlaveKey2();
                if (code.equals("0") || code.equals("1") || code.equals("2") || code.equals("3") || code.equals("7")) {
                    total += saveModel.getResult2();
                }
            } else if (index.equals("16")) {
                String code = saveModel.getSlaveKey2();
                if (!code.equals("2")) {
                    total += saveModel.getResult2();
                }
            } else {
                total += saveModel.getResult2();
            }
            resultList.add(map);
        }
        if (!index.equals("8")) {
            if (index.equals("36")) {
                //如果是查询36的指标 那么除数是签约总数
                List<SaveModel> list2 =findOneDateQuotaLevel1(endDate,endDate, area, level, "1","2",null,null,null);
                Integer num=0;
                if(list2.size()>0){
                    num = list2.get(0).getResult2();
                }else{
                    throw new Exception("param num error");
                }
                for (Map<String, Object> map:resultList) {
                    double rateG = (total > 0 ? ((long) map.get("amount")) * 1.0000 / num * 100 : 0);
                    map.put("rate", df.format(rateG));
                    map.put("rateString", ((long) map.get("amount")) + "/" + num);
                }
            }else{
                for (Map<String, Object> map:resultList) {
                    double rateG = (total > 0 ? ((long) map.get("amount")) * 1.0000 / total * 100 : 0);
                    map.put("rate", df.format(rateG));
                    map.put("rateString", ((int) map.get("amount")) + "/" + total);
                }
            }
        }
        if (index.equals("6") && resultList.size() > 0) {
            int i = 0;
            boolean flag = false;
            for (; i < resultList.size(); i++) {
                if (resultList.get(i).get("code") != null && String.valueOf(resultList.get(i).get("code")).equals("3")
                        && String.valueOf(resultList.get(i).get("amount")).equals("0")) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                resultList.remove(i);
            }
        }
        return new JSONArray(resultList);
    }
    public PopulationBase getPopulationBase(String code, String year) {
        String sql = "select * from wlyy_people_num where code=? and year=? ";
        List<PopulationBase> peopleNum = jdbcTemplate.query(sql, new BeanPropertyRowMapper(PopulationBase.class), code, year);
        if (peopleNum != null && peopleNum.size() > 0) {
            return peopleNum.get(0);
        } else {
            return null;
        }
    }
    /**
     * 获取一级指标达到量
     *
     * @param endDate 截止日期
     * @param area    区域
     * @param index   指标
     * @param level   级别
     * @return
     */
    public long getIndexTotal(String endDate, String area, int level, String index,String timeLevel) throws Exception{
        endDate = changeDate(endDate);
//        List<SaveModel> list =findOneDateQuotaLevel1("",endDate, area, level, index,timeLevel,null,null);
        List<SaveModel> list =findOneDateQuotaLevel0(endDate,endDate, area, level, index,timeLevel,null,null);
//        List<SaveModel> list =elasticsearchUtil.excute(sql.toString(),SaveModel.class,"","");
        if(list.size()>0){
            return list.get(0).getResult2();
        }
        return 0;
    }
    /**
     * 获取缴费
     *
     * @param endDate 截止日期
     * @param area    区域
     * @param level   级别
     * @return
     */
    public long getWeiJiaoFei(String endDate, String area, int level) {
//        List<SaveModel> list = findOneDateQuotaLevel2(endDate,area,level,"16","2","0");
//        if(list.size()>0){
//            return list.get(0).getResult2();
//        }
        return 0;
    }
    public JSONObject getRenewPercent(String level, String area, String year) {
        String renewIndex = "";
        if ("1".equals(level)) {
            //团队的续签量
            renewIndex = "42";
        } else if ("2".equals(level)) {
            //社区的续签量
            renewIndex = "43";
        } else if ("3".equals(level)) {
            //区的续签量
            renewIndex = "44";
        } else {
            //市的续签量
            renewIndex = "29";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        String todayString = simpleDateFormat.format(today);
        todayString = changeDate(todayString);
//        List<SaveModel> list = findOneDateQuotaLevel1(todayString,area,Integer.parseInt(level),renewIndex,"2",null,null);
        return null;
    }
}

+ 2 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java

@ -260,7 +260,8 @@ public class DoctorFeldsherTemplateService extends BaseService {
            Doctor doctor = doctorDao.findByCode(doctorCode);
            String doctorName = doctor.getName();
            String doctorOpenId = doctor.getOpenid();
//            String doctorOpenId = doctor.getOpenid();
            String doctorOpenId = "o7NFZw1QM4YR1O19mLjwfX1Hh11A";
            String first = businessType;
            sendJson.put("keyword1", content);

+ 11 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/jw/JwMaternalChildService.java

@ -7,10 +7,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2017/9/25.
@ -24,6 +26,8 @@ public class JwMaternalChildService {
    private String jwUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 获取孕妇建卡信息
@ -38,6 +42,13 @@ public class JwMaternalChildService {
        params.add(new BasicNameValuePair("idcard", idcard));
        params.add(new BasicNameValuePair("hospital", hospital));
        if(idcard.contains("352124761015122-")){
            String temp[] = idcard.split("-");
            String sql = "SELECT response FROM wlyy_zy_push_log_detail WHERE id = "+temp[1];
            List<Map<String ,Object>> list = jdbcTemplate.queryForList(sql);
            return list.get(0).get("response").toString();
        }
        String response = httpClientUtil.post(url, params, "UTF-8");
        return response;

+ 19 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/jw/ZyDictService.java

@ -8,6 +8,7 @@ import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.zydict.ZyCommonDictDao;
import com.yihu.wlyy.repository.zydict.ZyIvPhysicDictDao;
import com.yihu.wlyy.repository.zydict.ZyZoneDictDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
@ -36,6 +37,8 @@ public class ZyDictService {
    private ZyIvPhysicDictDao zyIvPhysicDictDao;
    @Autowired
    private ZyCommonDictDao zyCommonDictDao;
    @Autowired
    private ZyZoneDictDao zyZoneDictDao;
    @Transactional
    public void synchronousDict(String dictName) {
@ -112,6 +115,22 @@ public class ZyDictService {
        return null;
    }
    /**
     * 获取智业行政区域字典
     * @param zoneCode
     * @return
     */
    public String findZoneName(String zoneCode){
        String sql = "SELECT dm.zone_name" +
                " from zy_zone_dict dm " +
                " WHERE dm.zone_code = ? ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,zoneCode);
        if(list!=null&&list.size()>0){
            return list.get(0).get("zone_name").toString();
        }
        return "";
    }
    /**
     * 是否冷藏
     * @param physicCode

+ 0 - 129
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java

@ -1,129 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.common;
import org.springframework.context.annotation.Configuration;
/**
 * User: hzp
 * Date: 20170518
 * 这里放置各种配置数据
 */
@Configuration
public class Configure {
	/******************************* 易联众统一支付平台 ***********************************************************/
//	private String onepayApi = "http://120.42.37.94:1301/onepay-web/";
//	private String onepayAppId = "1BGKM1UHM03P7B2CA8C000005626EB0E";
//	private String onepayAppSecret = "1BGKM1UHM03I7B2CA8C00000AB682E9A";
//			开发环境应用信息
//	private String onepayApi = "https://xmhealth.ylzpay.com:8080/";
	private String onepayApi = "http://xmhealth.ylzpay.com:8070/";
	private String onepayAppId = "1BLF5SEGN00087165F0A000027362BE5";
	private String onepayAppSecret = "1BLF5SCBO01V3E78A8C00000F3A0FFE7";
	private String bindCardType = "onepay.sicard.bind.info";
	private String chargeType = "onepay.trade.medical.charge";
	private String chargeQueryType = "onepay.trade.medical.charge.query";
	private String createSicardType = "onepay.sicard.createurl";
//	易联众异步回调
	private String receiveNotify = "wlyy.onepay.receiveNotify";
	private String returnUrl = "wlyy.onepay.returnUrl";
//  长处方系列
	private String recipeChargeType = "onepay.trade.long.recipe.charge";
	private String recipeReturnUrl = "wlyy.patient.prescription.pay.recipeReturnUrl";
	private String receiveRecipeNotify = "wlyy.patient.prescription.pay.receiveRecipeNotify";
	public String getRecipeChargeType() {
		return recipeChargeType;
	}
	public void setRecipeChargeType(String recipeChargeType) {
		this.recipeChargeType = recipeChargeType;
	}
	public String getRecipeReturnUrl() {
		return recipeReturnUrl;
	}
	public void setRecipeReturnUrl(String recipeReturnUrl) {
		this.recipeReturnUrl = recipeReturnUrl;
	}
	public String getReceiveRecipeNotify() {
		return receiveRecipeNotify;
	}
	public void setReceiveRecipeNotify(String receiveRecipeNotify) {
		this.receiveRecipeNotify = receiveRecipeNotify;
	}
	public String getReturnUrl() {
		return returnUrl;
	}
	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
	public String getReceiveNotify() {
		return receiveNotify;
	}
	public void setReceiveNotify(String receiveNotify) {
		this.receiveNotify = receiveNotify;
	}
	public String getOnepayApi() {
		return onepayApi;
	}
	public String getOnepayAppId() {
		return onepayAppId;
	}
	public String getOnepayAppSecret() {
		return onepayAppSecret;
	}
	public String getBindCardType() {
		return bindCardType;
	}
	public String getChargeType() {
		return chargeType;
	}
	public String getChargeQueryType() {
		return chargeQueryType;
	}
	public String getCreateSicardType() {
		return createSicardType;
	}
	/******************* 微信社保支付配置 ******************************************/
	//这个就是自己要保管好的私有Key了(切记只能放在自己的后台代码里,不能放在任何可能被看到源代码的客户端程序中)
	// 每次自己Post数据给API的时候都要用这个key来对所有字段进行签名,生成的签名会放在Sign这个字段,API收到Post数据的时候也会用同样的签名算法对Post过来的数据进行签名和验证
	// 收到API的返回的时候也要用这个key来对返回的数据算下签名,跟API的Sign数据进行比较,如果值不一致,有可能数据被第三方给篡改
	private String key = "2935b54b53a957d9516c920a544f2537";
	//微信分配的公众号ID(开通公众号之后可以获取到)
	private String appID = "wxd03f859efdf0873d";
	public String getKey(){
		return key;
	}
	public String getAppid(){
		return appID;
	}
	//获取token地址
	public String TOKEN_API = "https://api.weixin.qq.com/payinsurance/gettoken";
	//挂号/诊间支付统一下单 API 接口
	public String ORDER_API = "https://api.weixin.qq.com/payinsurance/unifiedorder?access_token ACCESS_TOKEN";
}

+ 191 - 64
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/weixin/wxpay/service/OnePayService.java

@ -9,14 +9,14 @@ import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.ylz.PayConfigura;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.third.httplog.LogService;
import com.yihu.wlyy.repository.ylz.PayConfiguraDao;
import com.yihu.wlyy.service.third.ylz.PayLogService;
import com.yihu.wlyy.service.weixin.wxpay.common.Configure;
import com.yihu.wlyy.service.weixin.wxpay.model.BindCard;
import com.yihu.wlyy.service.weixin.wxpay.model.Charge;
import com.yihu.wlyy.util.SystemConf;
@ -25,7 +25,6 @@ import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.domain.RequestParams;
import com.ylzinfo.onepay.sdk.domain.ResponseParams;
import com.ylzinfo.onepay.sdk.utils.DateUtil;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -48,7 +47,7 @@ import java.util.*;
public class OnePayService {
    @Autowired
    private Configure config;
    private PayConfiguraDao configuraDao;
    @Autowired
    private PayLogService logService;
@ -137,12 +136,14 @@ public class OnePayService {
        String response = "";
        String error = "";
        List<BindCard> result = new ArrayList<BindCard>();
        String appId = config.getOnepayAppId();
        String appSecret = config.getOnepayAppSecret();
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
        PayConfigura config = configuraDao.findWorkConfigura();
        try {
            String appId = config.getOnepayAppId();
            String appSecret = config.getOnepayAppSecret();
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
            RequestParams requestParams = new RequestParams();
//            requestParams.setTransType();
//            requestParams.setVersion();
@ -196,22 +197,19 @@ public class OnePayService {
    /**
     * 家庭医生签约支付
     */
    public String charge(String orgCode, String chargeType, String chargeRelation, String totalAmount, String patient, String openid, String accessToken) throws Exception {
    public String charge(String orgCode, String chargeType, String chargeRelation, String totalAmount, String patient, String repUid, String openid, String accessToken) throws Exception {
        //获取机构映射
        HospitalMapping hos = hospitalMappingDao.findByCode(orgCode);
        if (hos == null) {
            throw new Exception("no hospital mapping!");
        }
        return charge(orgCode, hos.getName(), hos.getAppId(), hos.getAppSecret(),hos.getSbCode(), chargeType, chargeRelation, totalAmount,patient, openid,accessToken);
//        对应机构的APPID和appsecret
//        return charge(orgCode, hos.getName(), "54BBAF5148521AC9E053F000660AC502", "54BBAF5148531AC9E053F000660AC502",hos.getSbCode(), chargeType, chargeRelation, totalAmount,patient, openid,accessToken);
//        return charge(orgCode, hos.getName(), "54BBAF5148521AC9E053F000660AC502", "54BBAF5148531AC9E053F000660AC502", "0380", chargeType, chargeRelation, totalAmount, patient, openid, accessToken);
        return charge(orgCode, hos.getName(), hos.getAppId(), hos.getAppSecret(), hos.getSbCode(), chargeType, chargeRelation, totalAmount, patient, repUid, openid, accessToken);
    }
    /**
     * 家庭医生签约支付,成功则返回支付路径
     */
    private String charge(String orgCode, String orgName, String appId, String appSecret, String sbCode, String chargeType, String chargeRelation, String totalAmount, String patient, String openid, String accessToken) throws Exception {
    private String charge(String orgCode, String orgName, String appId, String appSecret, String sbCode, String chargeType, String chargeRelation, String totalAmount, String patient, String repUid, String openid, String accessToken) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
@ -219,20 +217,22 @@ public class OnePayService {
        String result = "";
        String channel = "WX_MMP";   //  医保支付渠道
        String subject = "家庭医生签约支付";   //  订单名称
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
//     未真正完成支付以前预存储支付信息到wlyy_charge表
        WlyyCharge charge = new WlyyCharge();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        charge.setChargeType(chargeType);   //交易类型
        charge.setChargeRelation(chargeRelation);  //交易关联代码 wlyy_sign_family字段code
        charge.setCode(uuid);  //  接入应用支付业务流水号
        Date now = new Date();
        charge.setCreateTime(now);
        charge.setPatient(patient);     //  用户
        charge.setOpenid(openid);     //  用戶微信openid
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        PayConfigura config = configuraDao.findWorkConfigura();
        try {
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
            String uuid = format.format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
            charge.setChargeType(chargeType);   //交易类型
            charge.setChargeRelation(chargeRelation);  //交易关联代码 wlyy_sign_family字段code
            charge.setCode(uuid);  //  接入应用支付业务流水号
            Date now = new Date();
            charge.setCreateTime(now);
            charge.setPatient(patient);     //  用户
            charge.setOpenid(openid);     //  用戶微信openid
            charge.setHospital(orgCode);
            charge.setHospitalName(orgName);
            charge.setChannel(channel);
@ -250,8 +250,7 @@ public class OnePayService {
            charge.setIdNo(idNo);
            charge.setSsc(ssc);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String currentDateTime = formatter.format(now);
            String currentDateTime = format.format(now);
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
@ -284,9 +283,6 @@ public class OnePayService {
            params.put("subject", subject);  //订单名称
            params.put("wxToken", accessToken);
            //extendParams 扩展入参
            //家庭医生签约信息
            //      根据签约code查询签约信息
            SignFamily signFamily = signFamilyDao.findByCode(chargeRelation);
            if (signFamily != null) {
@ -296,37 +292,44 @@ public class OnePayService {
                Doctor doctor = doctorDao.findByCode(signDoctorCode);
                Patient user = patientDao.findByCode(people);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                Map<String, String> familyContent = new HashMap<>();
//                familyContent.put("moRegNo", chargeRelation);//医院签约号限长20  signFamily code
                String moregNo = sdf.format(new Date())+ uuid.substring(0,6);
                String moregNo = format.format(new Date()) + uuid.substring(0, 6);
                familyContent.put("moRegNo", moregNo);//医院签约号限长20  signFamily code
                familyContent.put("moRegName",signFamily.getName()); //签约人姓名
//                familyContent.put("moRegName", "沈在鑫"); //签约人姓名
                familyContent.put("moRegName", signFamily.getName()); //签约人姓名
                familyContent.put("moRegAddr", user.getAddress()); //签约人地址
                familyContent.put("moRegTelephone", signFamily.getMobile());//签约人联系电话
                familyContent.put("moRegOrgNo", sbCode); //签约机构 限长4
                familyContent.put("moRegDocNo", doctor.getIdcard());//签约医生编号 限长18 身份证号
                familyContent.put("moRegDocName", signFamily.getSignDoctorName()); //签约医生姓名
                familyContent.put("moRegTime", sdf.format(signFamily.getBegin())); //签约时间
                familyContent.put("moRegEndTime", sdf.format(signFamily.getEnd())); //签约截止时间
//            familyContent.put("moRegYear", "04");//签约年度
                familyContent.put("moRegTime", format.format(signFamily.getBegin())); //签约时间
                familyContent.put("moRegEndTime", format.format(signFamily.getEnd())); //签约截止时间
                familyContent.put("moRegTear", signFamily.getSignYear());//签约年度
                familyContent.put("moRegSource", signFamily.getSignSource()); //签约来源
                familyContent.put("moCollectOrgNo", sbCode); //扣费机构 签约机构
                familyContent.put("moCollectorNo", signFamily.getSignDoctorName());//扣费人 签约医生姓名
                familyContent.put("benefitType", signFamily.getExpensesType()); //补贴类型
//                familyContent.put("benefitType", "01"); //补贴类型
                familyContent.put("moBookOrgNo", sbCode);//登记机构 签约机构
                familyContent.put("moBookerNo", signFamily.getSignDoctorName()); //登记人 签约医生姓名
                familyContent.put("moBookTime", sdf.format(signFamily.getBegin())); //登记时间 签约时间
                familyContent.put("moBookTime", format.format(signFamily.getBegin())); //登记时间 签约时间
                params.put("familyContent", objectMapper.writeValueAsString(familyContent));// 家庭医生签约信息
            }
            //请求结构体
            Map<String, String> map = new HashMap<>();
            map.put("feeType", "04");//家庭医生签约
            map.put("settleType", "03"); //健康账户支付
            //易联众新增字段v1.3.7
            map.put("principalCardNo", ssc); //实际签约卡号( 默认为绑卡主体卡号)
            charge.setPrincipalSsc(ssc);
            if (!patient.equals(repUid)) {
                Patient people = patientDao.findByCode(repUid);
                String repOpenId = people.getOpenid();
                BindCard repCard = ownerCard(repOpenId);
                String repSsc = repCard.getAttachCardNo();
                map.put("principalCardNo", repSsc); //实际签约卡号( 默认为绑卡主体卡号)
                charge.setPrincipalSsc(repSsc);
            }
            params.put("requestContent", objectMapper.writeValueAsString(map));// 请求结构体
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
@ -356,7 +359,6 @@ public class OnePayService {
        chargeDao.save(charge);
        //保存http日志
//        logService.saveHttpLog(isSuccess, config.getChargeType(), "家庭医生签约支付", "POST", null, msgBody, response, error, logService.onepayType);
        logService.saveHttpLog(isSuccess, config.getChargeType(), "家庭医生签约支付", "POST", null, msgBody, response, error, logService.onepayType);
        if (!isSuccess) {
@ -375,19 +377,19 @@ public class OnePayService {
        String response = "";
        String error = "";
        String result = null;
        PayConfigura config = configuraDao.findWorkConfigura();
        WlyyCharge charge = chargeDao.findByCode(code);
        HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
//        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), "54BBAF5148521AC9E053F000660AC501", "54BBAF5148531AC9E053F000660AC501", signType, encryptType);
        try {
            WlyyCharge charge = chargeDao.findByCode(code);
            HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
//            requestParams.setAppId(appId);
            requestParams.setAppId(hospitalMapping.getAppId());
//            requestParams.setAppId("54BBAF5148521AC9E053F000660AC501");
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
@ -410,10 +412,132 @@ public class OnePayService {
//                result = JSON.toJavaObject(res.getParam(), Charge.class);
                result = JSON.toJSONString(res.getParam());
//                 返回医保机构体
//                 新增保存数据
                JSONObject request = JSON.parseObject(result);
                String chargeStatus = request.getString("chargeStatus");//交易状态
                String chargeNo = request.getString("chargeNo");//支付平台流水号
                String chargeTime = request.getString("chargeTime");//支付平台交易成功时间
                String outChargeNo = request.getString("outChargeNo");//接入应用业务流水号
                String outChargeTime = request.getString("outChargeTime");//接入应用时间
                String medOrgNo = request.getString("medOrgNo");//医疗机构编号
                String medOrgName = request.getString("medOrgName");//医疗机构名称
                String billNo = request.getString("billNo");//待结算费用单据号
                String cardNo = request.getString("cardNo");//医保卡号
                String totalAmount = request.getString("totalAmount");//交易总金额
                String insuranceAmount = request.getString("insuranceAmount");//医保支付金额
                String selfPayAmount = request.getString("selfPayAmount");//自付金额
                String userId = request.getString("userId");//用户openID
                String userName = request.getString("userName");//用户名字
                String idType = request.getString("idType");//证件类型
                String idNo = request.getString("idNo");//证件号码
//                String appId = request.getString("appId");
//                String channel = request.getString("channel");//支付方式
//                String sign = request.getString("sign");
//                String signType = request.getString("signType");
//                String timestamp = request.getString("timestamp");
                WlyyCharge chargePay = chargeDao.findByCode(outChargeNo);
                if (request.containsKey("responseContent")){
                    JSONObject responseContents = request.getJSONObject("responseContent");//医保结构体
                    if (responseContents != null) {
                        String miRegisterNo = null;//医保挂号
                        String miCollectDate = null;//收费日期
                        String miCollectTime = null;//收费时间
                        String miSettleNo = null;//医保收费单据号 (医保签约号)
                        String miCollectStatus = null;//扣费状态
                        String miRegisterStatus = null;//登记状态
                        String cadresPay = "0";//公务员补助
                        String miTotalFee = "0";//本次报销总额
                        String healthCarePay = "0";//保健基金支付
                        String heathPay = "0";//健康账户支付
                        String accountPay = "0";//个人账户支付
                        String selfPay = "0";//个人现金支付
                        String civilPay = "0";//民政补助金额
                        if (responseContents.containsKey(miRegisterNo)) {
                            miRegisterNo = responseContents.getString("miRegisterNo");
                        }
                        if (responseContents.containsKey(miCollectDate)) {
                            miCollectDate = responseContents.getString("miCollectDate");
                        }
                        if (responseContents.containsKey(miCollectTime)) {
                            miCollectTime = responseContents.getString("miCollectTime");
                        }
                        if (responseContents.containsKey(miSettleNo)) {
                            miSettleNo = responseContents.getString("miSettleNo");
                        }
                        if (responseContents.containsKey(miCollectStatus)) {
                            miCollectStatus = responseContents.getString("miCollectStatus");
                        }
                        if (responseContents.containsKey(miRegisterStatus)) {
                            miRegisterStatus = responseContents.getString("miRegisterStatus");
                        }
                        if (responseContents.containsKey(cadresPay)) {
                            cadresPay = responseContents.getString("cadresPay");
                        }
                        if (responseContents.containsKey(miTotalFee)) {
                            miTotalFee = responseContents.getString("miTotalFee");
                        }
                        if (responseContents.containsKey(healthCarePay)) {
                            healthCarePay = responseContents.getString("healthCarePay");
                        }
                        if (responseContents.containsKey(heathPay)) {
                            heathPay = responseContents.getString("heathPay");
                        }
                        if (responseContents.containsKey(accountPay)) {
                            accountPay = responseContents.getString("accountPay");
                        }
                        if (responseContents.containsKey(selfPay)) {
                            selfPay = responseContents.getString("selfPay");
                        }
                        if (responseContents.containsKey(civilPay)) {
                            civilPay = responseContents.getString("civilPay");
                        }
                        chargePay.setMiRegisterNo(miRegisterNo);//医保挂号
                        chargePay.setMiCollectDate(miCollectDate);
                        chargePay.setMiCollectTime(miCollectTime);
                        chargePay.setMiSettleNo(miSettleNo);
                        chargePay.setMiCollectStatus(miCollectStatus);
                        chargePay.setMiRegisterStatus(miRegisterStatus);
                        chargePay.setCadresPay(cadresPay);
                        chargePay.setMiTotalFee(miTotalFee);
                        chargePay.setHealthCarePay(healthCarePay);
                        chargePay.setHeathPay(heathPay);
                        chargePay.setAccountPay(accountPay);
                        chargePay.setSelfPay(selfPay);
                        chargePay.setCivilPay(civilPay);
                }
//                System.out.println("请求成功,返回参数:" + result.getTradeStatus() + "  " + result.getUserName());
                LOGGER.info("请求成功,返回参数: "+result);
                }
                if ("0".equals(chargeStatus) || "SUCCESS".equals(chargeStatus)) {
                    chargePay.setTradeStatus("1");//交易状态 成功1 失败0
                } else {
                    chargePay.setTradeStatus("0");//交易状态 成功1 失败0
                }
                chargePay.setChargeNo(chargeNo);//支付流水号
                SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmmss");
                chargePay.setChargeTime(chargeTime);//支付平台交易成功时间
                chargePay.setCreateTime(formatDate.parse(outChargeTime));//接入应用内业务时间
                chargePay.setMedOrgNo(medOrgNo);//医疗机构编号
                chargePay.setMedOrgName(medOrgName);//医疗机构名称
                chargePay.setBillNo(billNo);//待结算费用单据号
                chargePay.setSsc(cardNo);//医保卡号
                chargePay.setTotalAmount(Integer.parseInt(totalAmount));//交易总金额
                chargePay.setInsuranceAmount(Integer.parseInt(insuranceAmount));//医保支付金额
                chargePay.setSelfpayAmount(Integer.parseInt(selfPayAmount));//自付金额
                chargePay.setOpenid(userId);
                chargePay.setName(userName);
                chargePay.setIdType(idType);//证件类型
                chargePay.setIdNo(idNo);//证件号码
                //        保存数据库更改记录
                chargeDao.save(chargePay);
                LOGGER.info("请求成功,返回参数: " + result);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
@ -439,18 +563,22 @@ public class OnePayService {
    /**
     * 生成电子社保卡
     */
    public String createSicard(String patient, String openid) throws Exception {
    public String createSicard(String patient, String openid, String createType) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = "";
        String appId = config.getOnepayAppId();
        String appSecret = config.getOnepayAppSecret();
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
        PayConfigura config = null;
        try {
            config = configuraDao.findWorkConfigura();
            String appId = config.getOnepayAppId();
            String appSecret = config.getOnepayAppSecret();
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
            RequestParams requestParams = new RequestParams();
            requestParams.setAppId(appId);
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
@ -463,6 +591,8 @@ public class OnePayService {
            JSONObject params = new JSONObject();
            params.put("openId", openid);
            params.put("accId", accId);  //微信公众号开发者ID
//           易联众新增字段代支付v1.3.7
            params.put("createType", createType);  //生成类型 sicard 个人电子社保卡 OR family 家庭成员绑卡 ( 默认 sicard)
            requestParams.setParam(params);
            requestParams.setTransType(config.getCreateSicardType());
@ -558,15 +688,12 @@ public class OnePayService {
    /**
     * 更改数据 wlyy_sign_family wlyy_charge
     */
    public void updateData(String chargeCode, String chargeNo, String chargeTime, String totalAmount, String insuranceAmount, String selfPayAmount, String billNo, String miRegisterNo) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date chargeSuccess = sdf.parse(chargeTime);
        Date updateTime = new Date();
        chargeDao.updateByChargeCode(chargeCode, chargeTime, updateTime, Integer.parseInt(totalAmount), Integer.parseInt(insuranceAmount), Integer.parseInt(selfPayAmount),
                billNo, miRegisterNo, "0");
//        根据wlyy_charge的code 去查找关联代码signCode在更新签约表
        WlyyCharge charge = chargeDao.findByCode(chargeCode);
        signFamilyDao.updatePatientBegin(charge.getChargeRelation(), chargeSuccess, chargeNo, "1",2);
    public void updateData(String chargeStatus, Date chargeTime, String chargeNo, WlyyCharge charge) throws Exception {
        chargeDao.save(charge);
//        成功支付根据wlyy_charge的code 去查找关联代码signCode在更新签约表
        if ("0".equals(chargeStatus)) {
            signFamilyDao.updatePatientBegin(charge.getChargeRelation(), chargeTime, chargeNo, "1", 2);
        }
    }
}

+ 14 - 7
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java

@ -59,9 +59,15 @@ public class ElasticsearchUtil {
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getHits(), true);
            Object queryResult = null;
            if(sql.toUpperCase().indexOf("GROUP")!=-1||sql.toUpperCase().indexOf("SUM")!=-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 -> {
            temp.getLines().forEach(one -> {
                Object saveModel = null;
                try {
                    saveModel = clazz.newInstance();
@ -75,11 +81,12 @@ public class ElasticsearchUtil {
                        if(heads.get(i).startsWith("_")){
                            continue;
                        }
                        if (heads.get(i).contains("date_histogram")) {
                            key = "setQuotaDate";
                            value = DateUtil.strToDate(String.valueOf(value), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            key = "set" + UpFirstStr(heads.get(i));
                        key = "set" + UpFirstStr(heads.get(i));
                        if (heads.get(i).contains("quotaDate")||heads.get(i).contains("createTime")||heads.get(i).contains("date_histogram")) {
                            if(heads.get(i).contains("date_histogram")){
                                key = "setQuotaDate";
                            }
                            value = DateUtil.strToDate(String.valueOf(value).replace("T00:00:00+0800"," 00:00:00"), "yyyy-MM-dd HH:mm:ss");
                        }
                        if (value instanceof String) {

+ 8 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/prenatalInspector/PrenatalInspectorContoller.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
@ -40,8 +41,11 @@ public class PrenatalInspectorContoller extends BaseController{
            if("-1".equals(code)){
                return error(-1,"居民未签约,无法添加预建卡信息");
            }
            preCardService.uploadPreExam(code);
            String re = preCardService.uploadPreExam(code);
            if(StringUtils.isNotBlank(re)){
                System.out.println("re======"+re);
                return error(-1,re);
            }
            return success("预建卡保存成功!");
        }catch (Exception e){
            error(e);
@ -95,8 +99,8 @@ public class PrenatalInspectorContoller extends BaseController{
    @RequestMapping(value = "preCardList", method = RequestMethod.GET)
    public String preCardList(){
        try {
//            JSONArray jsonArray = preCardService.preCardList(getUID());
            JSONArray jsonArray = preCardService.preCardList("915cca0a-5b1d-11e6-8344-fa163e8aee56");
            JSONArray jsonArray = preCardService.preCardList(getUID());
//            JSONArray jsonArray = preCardService.preCardList("915cca0a-5b1d-11e6-8344-fa163e8aee56");
            return write(200, "查询成功!", "list", jsonArray);
        }catch (Exception e){
            error(e);
@ -110,7 +114,6 @@ public class PrenatalInspectorContoller extends BaseController{
            @RequestParam(value = "inspectionCode", required = true) String inspectionCode){
        try {
            JSONArray jsonArray = preCardService.planList(inspectionCode);
            preCardService.sendPrenatalInspectorRemind();
            return write(200, "查询成功!", "list", jsonArray);
        }catch (Exception e){
            error(e);

+ 6 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/prescription/PatientPrescriptionPayController.java

@ -84,11 +84,14 @@ public class PatientPrescriptionPayController extends WeixinBaseController {
        try {
            String accessToken = getAccessToken();
            String patient = getUID();
            Map result = payService.charge(type, addressJson, orgCode, prescriptionCode, totalAmount, patient, accessToken, returnUrl,deliveryTime);
            String repUid = getRepUID();
            Map result = payService.charge(type, addressJson, orgCode, prescriptionCode, totalAmount, patient, repUid, accessToken, returnUrl, deliveryTime);
            if ("-1".equals(result.get("status").toString())) {
                return error(-1, "续方居民信息与微信支付身份信息不一致!");
            } else if ("-2".equals(result.get("status").toString())) {
                return error(-1, "续方居民信息挂号号或处方号不存在!");
            } else if ("-3".equals(result.get("status").toString())) {
                return error(-1, "您没有需要待结算的信息!");
            } else {
                return write(200, "支付成功!", "data", result);
            }
@ -165,9 +168,9 @@ public class PatientPrescriptionPayController extends WeixinBaseController {
            @ApiParam(name = "visitNo", value = "挂号号", defaultValue = "3277865")
            @RequestParam(value = "visitNo", required = true) String visitNo,
            @ApiParam(name = "recipeNo", value = "基卫处方号", defaultValue = "3277865")
            @RequestParam(value = "recipeNo", required = true) String recipeNo){
            @RequestParam(value = "recipeNo", required = true) String recipeNo) {
        try {
            com.alibaba.fastjson.JSONObject jsonParams = prescriptionService.getPayInfo(cardNo, visitNo,recipeNo);
            com.alibaba.fastjson.JSONObject jsonParams = prescriptionService.getPayInfo(cardNo, visitNo, recipeNo);
            return write(200, "获取成功!", "data", jsonParams);
        } catch (Exception e) {
            return error(-1, "获取失败!");

+ 32 - 16
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java

@ -34,8 +34,8 @@ public class StatisticsController extends BaseController {
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    StatisticsESService statisticsESService;
//    @Autowired
//    StatisticsESService statisticsESService;
    @Autowired
    StatisticsAllService statisticsAllService;
@ -71,20 +71,19 @@ public class StatisticsController extends BaseController {
    @ResponseBody
    public String indexInterval(@RequestParam(required = true) String startDate,
                                @RequestParam(required = true) String endDate,
                                @RequestParam(required = true) int interval,
                                @RequestParam(required = true) String interval,
                                @RequestParam(required = true) String area,
                                @RequestParam(required = true) String level,
                                @RequestParam(required = true) int level,
                                @RequestParam(required = true) String index,
                                @RequestParam(required = false) String level2_type) {
        String tag = "";
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
            if (index != null) {
                for (String idx : indexes) {
                    result.put("index_" + idx, statisticsESService.getDateIncrementDetail(startDate, endDate, interval, area, level, idx, level2_type));
//                    result.put("index_" + idx, statisticsService.getDateIncrementDetail(startDate, endDate, interval, area, Integer.parseInt(level), idx, level2_type));
//                    result.put("index_" + idx, statisticsESService.getDateIncrementDetail(startDate, endDate, interval, area, level, idx, level2_type));
                    result.put("index_" + idx, statisticsService.getDateIncrementDetail(startDate, endDate, Integer.parseInt(interval), area, level, idx, level2_type));
                }
            }
@ -118,6 +117,7 @@ public class StatisticsController extends BaseController {
            JSONObject result = new JSONObject();
            for (String idx : indexes) {
//                result.put("index_" + idx, statisticsESService.getDateIncrementDetail(startDate, endDate, "", area, level, idx, ""));
                result.put("index_" + idx, statisticsService.getIntervalIncrement(startDate, endDate, area, level, idx));
            }
@ -154,6 +154,7 @@ public class StatisticsController extends BaseController {
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsService.getTotalAmount(startDate, endDate, area, level, idx, level2_type));
//                result.put("index_" + idx, statisticsESService.getTotalAmount(startDate, endDate, area, level, idx, level2_type));
            }
            return write(200, "查询成功", "data", result);
@ -227,6 +228,7 @@ public class StatisticsController extends BaseController {
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsService.getLowLevelTotalDetail(endDate, area, level, idx, sort, lowLevel, level2_type, year));
//                result.put("index_" + idx, statisticsESService.getLowLevelTotalDetail(endDate, area, level, idx, sort, lowLevel, level2_type, year));
            }
            return write(200, "查询成功", "data", result);
@ -261,9 +263,15 @@ public class StatisticsController extends BaseController {
            JSONArray returnJa = new JSONArray();
            List<JSONArray> jsonArrays = new ArrayList<>();
            JSONArray jsonArray1 = statisticsService.getLowLevelTotalDetail(endDate, area, level, indexes[0], sort, lowLevel, null, year);
            jsonArrays.add(jsonArray1);
            /**新版统计代码start**/
//            JSONArray jsonArray1 = statisticsESService.getLowLevelTotalDetail(endDate, area, level, indexes[0], sort, lowLevel, null, year);
//            jsonArrays.add(jsonArray1);
//            JSONArray jsonArray2 = statisticsESService.getLowLevelTotalDetail(endDate, area, level, indexes[1], sort, lowLevel, null, year);
//            jsonArrays.add(jsonArray2);
            /**新版统计代码end**/
            /**旧版统计代码start**/
            JSONArray jsonArray2 = null;
            if (Constant.getNowYearByDate(endDate).equals(year)) {
                jsonArray2 = statisticsService.getLowLevelIncrementDetail(endDate, endDate, area, level, indexes[1], sort, lowLevel);
@ -272,6 +280,7 @@ public class StatisticsController extends BaseController {
                jsonArray2 = statisticsService.getLowLevelIncrementDetail(date, date, area, level, indexes[1], sort, lowLevel);
            }
            jsonArrays.add(jsonArray2);
            /**旧版统计代码end**/
            //遍历合并2个指标中key值一样的
            if (jsonArrays.get(1).length() == 0) {
@ -354,6 +363,7 @@ public class StatisticsController extends BaseController {
            JSONObject result = new JSONObject();
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsAllService.getIndexLevelTwototal(endDate, area, level, idx));
//                result.put("index_" + idx, statisticsESService.getIndexLevelTwototal(endDate, area, level, idx));
            }
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
@ -395,6 +405,9 @@ public class StatisticsController extends BaseController {
                JSONObject signRate = statisticsAllService.getSignRate(endDate, area, level,year);
                JSONObject signTaskRate = statisticsAllService.getSignTaskRate(endDate, area, level,year);
//                long sign = statisticsESService.getIndexTotal(endDate, area, level, "13","2");
//                long weiJf = statisticsESService.getWeiJiaoFei(endDate, area, level);
//                JSONObject jo = statisticsESService.getRenewPercent(level + "", area, Constant.getNowYear());
                result.put("sign", sign);
                result.put("expenses", weiJf);
@ -1423,10 +1436,11 @@ public class StatisticsController extends BaseController {
     * 获取转签率和续签率
     * 前端:续签进展
     *
     * @param index 42,43,44
     * @param index 42,43,44 (52,53,54 服务类型维度)
     * @param level 等级  4 市  3区  2社区 1团队
     * @param code  市 默认是厦门市 350200  区 就是区的code  社区就是社区的code 团队就是团队的code
     * @param year  年份 非比传
     * @param lowCode 服务类型维度code(老年人3,高血压4,糖尿病5)
     * @return
     */
    @RequestMapping(value = "/getRenewPercentAndChangePercent", method = RequestMethod.GET)
@ -1435,10 +1449,11 @@ public class StatisticsController extends BaseController {
            @RequestParam(required = true) String index,//续签index
            @RequestParam(required = true) String level,
            @RequestParam(required = true) String code,
            @RequestParam(required = false) String year) {
            @RequestParam(required = false) String year,
            @RequestParam(required = false) String lowCode) {
        try {
            return write(200, "查询成功", "data", statisticsService.getRenewPercentAndChangePercent(index,level, code, year));
            return write(200, "查询成功", "data", statisticsService.getRenewPercentAndChangePercent(index,level, code, year,lowCode));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
@ -1516,12 +1531,13 @@ public class StatisticsController extends BaseController {
    /**
     * 去年的签约量,续签量和续签率 列表
     *
     * @param index      42,43,44
     * @param area    每个层级大的code  例如湖里区 350206  xx社区 3502060100
     * @param index    42,43,44 (52,53,54 服务类型维度)
     * @param area     每个层级大的code  例如湖里区 350206  xx社区 3502060100
     * @param level    level1_type等级 1:团队 2社区机构 3区级 4市级
     * @param sort     0:升序 1:降序
     * @param lowLevel  只有可能是 1,2,3,不传默认是level-1
     * @param year      不管根据当前时间找年度
     * @param lowLevel 只有可能是 1,2,3,不传默认是level-1;
     *                 如果是服务类型维度code(老年人3,高血压4,糖尿病5)
     * @param year     不管根据当前时间找年度
     * @return
     */
    @RequestMapping("/lowlevel_all_sign_renew")

+ 226 - 103
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/wx/OnePayController.java

@ -4,13 +4,15 @@ import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.ylz.PayConfigura;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.ylz.PayConfiguraDao;
import com.yihu.wlyy.service.third.httplog.LogService;
import com.yihu.wlyy.service.third.ylz.PayLogService;
import com.yihu.wlyy.service.weixin.wxpay.common.Configure;
import com.yihu.wlyy.service.weixin.wxpay.model.BindCard;
import com.yihu.wlyy.service.weixin.wxpay.model.Charge;
import com.yihu.wlyy.service.weixin.wxpay.service.OnePayService;
@ -25,6 +27,7 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -45,6 +48,8 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -70,38 +75,31 @@ public class OnePayController extends WeixinBaseController {
    @Autowired
    PayLogService logService;
    @Autowired
    private Configure config;
    private PayConfiguraDao configuraDao;
    @Autowired
    private HospitalMappingDao mappingDao;
    @Autowired
    ObjectMapper objectMapper;
    @RequestMapping(value = "createSicard", method = RequestMethod.POST)
    @ApiOperation("生成电子社保卡")
    @ResponseBody
    public String createSicard() throws Exception {
        try {
            String sicardUrl = pay.createSicard("0cc6e4562de2437ab2dbbf51a9fc3b49", "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc");//getUID(), getOpenid());
            return write(200, "生成电子社保卡成功!", "data", sicardUrl);
        } catch (Exception e) {
            error(e);
            return write(-1, "生成电子社保卡失败!");
        }
    }
    @RequestMapping(value = "bindCard", method = RequestMethod.POST)
    @ApiOperation("查询绑卡信息")
    @ResponseBody
    public String bindCard() throws Exception {
        try {
            String patient = getUID();
            String openid = getOpenid();
//            在鑫
//            String patient = "0cc6e4562de2437ab2dbbf51a9fc3b49";
//            String openid = "o7NFZw7FlRW-Hlp0VjM71FR_1otw";
            BindCard bindCard = pay.bindCard(patient, openid);//getUID(), getOpenid());      oULM4xAj9sOsHJ95ttKYd_Fjh6Hc
            String sicardUrl = pay.createSicard(patient, openid);//getUID(), getOpenid());
            String repUid = getRepUID();
            String uid = getUID();
            String patient = uid;
            String createType = "sicard";
            if (!repUid.equals(uid)) {
                patient = repUid;
                createType = "family";
            }
            Patient people = patientDao.findByCode(patient);
            String openid = people.getOpenid();
            BindCard bindCard = pay.bindCard(patient, openid);
            String sicardUrl = pay.createSicard(patient, openid, createType);
            if (bindCard != null) {
                JSONObject json = new JSONObject(bindCard);
                json.put("bindStatus", "000000");
@ -137,11 +135,10 @@ public class OnePayController extends WeixinBaseController {
            totalAmount = "9000";
            String patient = getUID();
            String openId = getOpenid();
//            在鑫
//            String patient = "0cc6e4562de2437ab2dbbf51a9fc3b49";
//            String openId = "o7NFZw7FlRW-Hlp0VjM71FR_1otw";
            String repUid = getRepUID();
            if (StringUtils.isNotEmpty(openId)) {
                String settleNo = pay.charge(orgCode, chargeType, chargeRelation, totalAmount, patient, openId, getAccessToken());  //ohNH9sh4uwuJCxIwcLJtGTX-BaSk    getUID(),getOpenid()
                String settleNo = pay.charge(orgCode, chargeType, chargeRelation, totalAmount, patient, repUid, openId, getAccessToken());
                return write(200, "家庭医生签约支付成功!", "data", settleNo);
            } else {
                return write(-1, "openId为空!");
@ -263,6 +260,8 @@ public class OnePayController extends WeixinBaseController {
     */
    @RequestMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, PayException {
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmmss");
        PayConfigura config = configuraDao.findWorkConfigura();
        Boolean isSuccess = false;
        String error = "";
        String responses = "";
@ -273,63 +272,117 @@ public class OnePayController extends WeixinBaseController {
            isSuccess = true;
            String appId = request.getParameter("appId");
            String billNo = request.getParameter("billNo");//待结算费用单据号
            String cardNo = request.getParameter("cardNo");//医保卡号
            String channel = request.getParameter("channel");//支付方式
            String timestamp = request.getParameter("timestamp");
            String chargeNo = request.getParameter("chargeNo");//支付平台流水号
            String chargeTime = request.getParameter("chargeTime");//支付平台交易成功时间
            String idNo = request.getParameter("idNo");//证件号码
            String idType = request.getParameter("idType");//证件类型
            String insuranceAmount = request.getParameter("insuranceAmount");//医保支付金额
            String outChargeNo = request.getParameter("outChargeNo");//接入应用业务流水号
            String outChargeTime = request.getParameter("outChargeTime");//接入应用时间
            String selfPayAmount = request.getParameter("selfPayAmount");//自付金额
            String sign = request.getParameter("sign");
            String signType = request.getParameter("signType");
            String timestamp = request.getParameter("timestamp");
            String channel = request.getParameter("channel");//支付方式
            String billNo = request.getParameter("billNo");//待结算费用单据号
            String cardNo = request.getParameter("cardNo");//医保卡号
            String totalAmount = request.getParameter("totalAmount");//交易总金额
            String tradeStatus = request.getParameter("tradeStatus");//交易状态
            String insuranceAmount = request.getParameter("insuranceAmount");//医保支付金额
            String selfPayAmount = request.getParameter("selfPayAmount");//自付金额
            String userId = request.getParameter("userId");//用户openID
            String userName = request.getParameter("userName");//用户名字
            String idType = request.getParameter("idType");//证件类型
            String idNo = request.getParameter("idNo");//证件号码
            String chargeStatus = request.getParameter("chargeStatus");//交易状态
            String sign = request.getParameter("sign");
            String signType = request.getParameter("signType");
            WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo);
            String result = pay.chargeQuery(outChargeNo, getAccessToken());//业务出参
            JSONObject param = new JSONObject(result);
            String requestParam = param.getString("responseContent");
            JSONObject responseContents = new JSONObject(requestParam);//医保结构体
            String miRegisterNo = "";
            String miCollectDate = "";
            String miCollectTime = "";
            String miSettleNo = "";
            String miCollectStatus = "";
            String miRegisterStatus = "";
            String cadresPay = "";
            String miTotalFee = "";
            String healthCarePay = "";
            String heathPay = "";
            String accountPay = "";
            String selfPay = "";
            if (responseContents != null) {
               miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号
                 miCollectDate = responseContents.getString("miCollectDate");//扣费日期
                 miCollectTime = responseContents.getString("miCollectTime");//扣费时间
                 miSettleNo = responseContents.getString("miSettleNo");//扣费单据号
                 miCollectStatus = responseContents.getString("miCollectStatus");//扣费状态
                 miRegisterStatus = responseContents.getString("miRegisterStatus");//登记状态
                 cadresPay = responseContents.getString("cadresPay");//政府补贴支付
                 miTotalFee = responseContents.getString("miTotalFee");//扣费总额
                 healthCarePay = responseContents.getString("healthCarePay");//医保统筹支付
                 heathPay = responseContents.getString("heathPay");//健康账户支付
                 accountPay = responseContents.getString("accountPay");//医保账户支付
                 selfPay = responseContents.getString("selfPay");//个人现金支付
            }
            charge.setChargeNo(chargeNo);
            charge.setChargeTime(chargeTime);
            charge.setCreateTime(formatDate.parse(outChargeTime));
            charge.setChannel(channel);
            charge.setBillNo(billNo);
            charge.setPrincipalSsc(cardNo);
            charge.setTotalAmount(Integer.parseInt(totalAmount));
            charge.setInsuranceAmount(Integer.parseInt(insuranceAmount));
            charge.setSelfpayAmount(Integer.parseInt(selfPayAmount));
            charge.setOpenid(userId);
            charge.setName(userName);
            charge.setIdType(idType);
            charge.setIdNo(idNo);
            charge.setTradeStatus(chargeStatus);
            if (param.has("responseContent") && (param.getJSONObject("responseContent") != null)) {
                String requestParam = param.getString("responseContent");
                JSONObject responseContents = new JSONObject(requestParam);//医保结构体
                String miRegisterNo = "";
                String miCollectDate = "";
                String miCollectTime = "";
                String miSettleNo = "";
                String miCollectStatus = "";
                String miRegisterStatus = "";
                String cadresPay = "";
                String miTotalFee = "";
                String healthCarePay = "";
                String heathPay = "";
                String accountPay = "";
                String selfPay = "";
                String civilPay = "";
                if (responseContents != null) {
                    if (responseContents.has("miRegisterNo")) {
                        miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号
                    }
                    if (responseContents.has("miCollectDate")) {
                        miCollectDate = responseContents.getString("miCollectDate");//扣费日期
                    }
                    if (responseContents.has("miCollectTime")) {
                        miCollectTime = responseContents.getString("miCollectTime");//扣费时间
                    }
                    if (responseContents.has("miSettleNo")) {
                        miSettleNo = responseContents.getString("miSettleNo");//扣费单据号
                    }
                    if (responseContents.has("miCollectStatus")) {
                        miCollectStatus = responseContents.getString("miCollectStatus");//扣费状态
                    }
                    if (responseContents.has("miRegisterStatus")) {
                        miRegisterStatus = responseContents.getString("miRegisterStatus");//登记状态
                    }
                    if (responseContents.has("cadresPay")) {
                        cadresPay = responseContents.getString("cadresPay");//政府补贴支付
                    }
                    if (responseContents.has("miTotalFee")) {
                        miTotalFee = responseContents.getString("miTotalFee");//扣费总额
                    }
                    if (responseContents.has("healthCarePay")) {
                        healthCarePay = responseContents.getString("healthCarePay");//医保统筹支付
                    }
                    if (responseContents.has("accountPay")) {
                        accountPay = responseContents.getString("accountPay");//医保账户支付
                    }
                    if (responseContents.has("selfPay")) {
                        selfPay = responseContents.getString("selfPay");//个人现金支付
                    }
                    if (responseContents.has("civilPay")) {
                        civilPay = responseContents.getString("civilPay");//基本卫生服务支付
                    }
                    charge.setMiRegisterNo(miRegisterNo);
                    charge.setMiCollectDate(miCollectDate);
                    charge.setMiCollectTime(miCollectTime);
                    charge.setMiSettleNo(miSettleNo);
                    charge.setMiCollectStatus(miCollectStatus);
                    charge.setMiRegisterStatus(miRegisterStatus);
                    charge.setCadresPay(cadresPay);
                    charge.setMiTotalFee(miTotalFee);
                    charge.setHealthCarePay(healthCarePay);
                    charge.setHeathPay(heathPay);
                    charge.setAccountPay(accountPay);
                    charge.setSelfPay(selfPay);
                    charge.setCivilPay(civilPay);
                }
            }
//                判断是否需要更新数据 needUpload为0不需要更新
            WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo);
            LOGGER.info("before  goto "+charge.getNeedUpload()+" == "+ outChargeNo);
            LOGGER.info("before  goto " + charge.getNeedUpload() + " == " + outChargeNo);
            if (charge != null && !("0".equals(charge.getNeedUpload()))) {
                pay.updateData(outChargeNo, chargeNo, chargeTime, totalAmount, insuranceAmount, selfPayAmount, billNo, miRegisterNo);
                LOGGER.info("after  goto "+charge.getNeedUpload()+" == "+ outChargeNo);
                pay.updateData(chargeStatus, formatDate.parse(chargeTime), chargeNo, charge);
                LOGGER.info("after  goto " + charge.getNeedUpload() + " == " + outChargeNo);
            }
        } catch (Exception e) {
@ -350,29 +403,31 @@ public class OnePayController extends WeixinBaseController {
     */
    @RequestMapping(value = "/receiveNotify")
    public void receiveNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, PayException {
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmmss");
        PayConfigura config = configuraDao.findWorkConfigura();
        Boolean isSuccess = false;
        String error = "";
        String responses = "";
        response.setContentType("text/html;charset=utf-8");
        InputStream inputStream = request.getInputStream();
        String params = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
        JSONObject json = new JSONObject(params);
        String appId = json.getString("appId");
        HospitalMapping hospital = mappingDao.findByAppId(appId);
        String appSecret = hospital.getAppSecret();
        try {
            JSONObject json = new JSONObject(params);
            String appId = json.getString("appId");
            HospitalMapping hospital = mappingDao.findByAppId(appId);
            String appSecret = hospital.getAppSecret();
//        String appSecret = json.getString("appId");
        LOGGER.info("回调参数:{}", params);
        if (StringUtil.isEmpty(params)) {
            response.getWriter().write("empty");
            return;
        }
        // 参数转换
        ResponseParams<?> encryptRes = JSON.parseObject(params, ResponseParams.class);
        OnepayDefaultClient client = new OnepayDefaultClient("", appId, appSecret, encryptRes.getSignType(), encryptRes.getEncryptType());
            LOGGER.info("回调参数:{}", params);
            if (StringUtil.isEmpty(params)) {
                response.getWriter().write("empty");
                return;
            }
            // 参数转换
            ResponseParams<?> encryptRes = JSON.parseObject(params, ResponseParams.class);
            OnepayDefaultClient client = new OnepayDefaultClient("", appId, appSecret, encryptRes.getSignType(), encryptRes.getEncryptType());
        try {
            LOGGER.info("解密前:{}", JSON.toJSONString(encryptRes));
            ResponseParams<?> decryptRes = client.decryptNotifyResponse(encryptRes);
            LOGGER.info("解密后:{}", JSON.toJSONString(decryptRes));
@ -406,33 +461,101 @@ public class OnePayController extends WeixinBaseController {
                    String userName = requestParam.getString("userName");//用户名字
                    String idType = requestParam.getString("idType");//证件类型
                    String idNo = requestParam.getString("idNo");//证件号码
                    String tradeStatus = requestParam.getString("tradeStatus");//交易状态
                    String chargeStatus = requestParam.getString("chargeStatus");//交易状态
                    WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo);
                    charge.setChargeNo(chargeNo);
                    charge.setChargeTime(chargeTime);
                    charge.setCreateTime(formatDate.parse(outChargeTime));
                    charge.setChannel(channel);
                    charge.setBillNo(billNo);
                    charge.setPrincipalSsc(cardNo);
                    charge.setTotalAmount(Integer.parseInt(totalAmount));
                    charge.setInsuranceAmount(Integer.parseInt(insuranceAmount));
                    charge.setSelfpayAmount(Integer.parseInt(selfPayAmount));
                    charge.setOpenid(userId);
                    charge.setName(userName);
                    charge.setIdType(idType);
                    charge.setIdNo(idNo);
                    charge.setTradeStatus(chargeStatus);
                    String miRegisterNo = "";//医保签约号
                    if (requestParams.has("responseContent") && (requestParams.getJSONObject("responseContent") != null)) {
                        JSONObject responseContents = requestParams.getJSONObject("responseContent");//医保结构体
                        miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号
                        String miCollectDate = responseContents.getString("miCollectDate");//扣费日期
                        String miCollectTime = responseContents.getString("miCollectTime");//扣费时间
                        String miSettleNo = responseContents.getString("miSettleNo");//扣费单据号
                        String miCollectStatus = responseContents.getString("miCollectStatus");//扣费状态
                        String miRegisterStatus = responseContents.getString("miRegisterStatus");//登记状态
                        String cadresPay = responseContents.getString("cadresPay");//政府补贴支付
                        String miTotalFee = responseContents.getString("miTotalFee");//扣费总额
                        String healthCarePay = responseContents.getString("healthCarePay");//医保统筹支付
//                responseContents.getString("healthPay");
                        String heathPay = responseContents.getString("heathPay");//健康账户支付
                        String accountPay = responseContents.getString("accountPay");//医保账户支付
                        String selfPay = responseContents.getString("selfPay");//个人现金支付
                        String miCollectDate = null;//扣费日期
                        String miCollectTime = null;//扣费时间
                        String miSettleNo = null;//扣费单据号
                        String miCollectStatus = null;//扣费状态
                        String miRegisterStatus = null;//登记状态
                        String cadresPay = "0";//政府补贴支付
                        String miTotalFee = "0";//扣费总额
                        String healthCarePay = "0";//医保统筹支付
                        String heathPay = "0";//健康账户支付
                        String accountPay = "0";//医保账户支付
                        String selfPay = "0";//个人现金支付
                        String civilPay = "0";//基本卫生服务支付
                        if (responseContents.has("miRegisterNo")) {
                            miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号
                        }
                        if (responseContents.has("miCollectDate")) {
                            miCollectDate = responseContents.getString("miCollectDate");
                        }
                        if (responseContents.has("miCollectTime")) {
                            miCollectTime = responseContents.getString("miCollectTime");
                        }
                        if (responseContents.has("miSettleNo")) {
                            miSettleNo = responseContents.getString("miSettleNo");
                        }
                        if (responseContents.has("miCollectStatus")) {
                            miCollectStatus = responseContents.getString("miCollectStatus");
                        }
                        if (responseContents.has("miRegisterStatus")) {
                            miRegisterStatus = responseContents.getString("miRegisterStatus");
                        }
                        if (responseContents.has("cadresPay")) {
                            cadresPay = responseContents.getString("cadresPay");
                        }
                        if (responseContents.has("miTotalFee")) {
                            miTotalFee = responseContents.getString("miTotalFee");
                        }
                        if (responseContents.has("healthCarePay")) {
                            healthCarePay = responseContents.getString("healthCarePay");
                        }
                        if (responseContents.has("heathPay")) {
                            heathPay = responseContents.getString("heathPay");
                        }
                        if (responseContents.has("accountPay")) {
                            accountPay = responseContents.getString("accountPay");
                        }
                        if (responseContents.has("selfPay")) {
                            selfPay = responseContents.getString("selfPay");
                        }
                        if (responseContents.has("civilPay")) {
                            civilPay = responseContents.getString("civilPay");
                        }
                        charge.setMiRegisterNo(miRegisterNo);
                        charge.setMiCollectDate(miCollectDate);
                        charge.setMiCollectTime(miCollectTime);
                        charge.setMiSettleNo(miSettleNo);
                        charge.setMiCollectStatus(miCollectStatus);
                        charge.setMiRegisterStatus(miRegisterStatus);
                        charge.setCadresPay(cadresPay);
                        charge.setMiTotalFee(miTotalFee);
                        charge.setHealthCarePay(healthCarePay);
                        charge.setHeathPay(heathPay);
                        charge.setAccountPay(accountPay);
                        charge.setSelfPay(selfPay);
                        charge.setCivilPay(civilPay);
                    }
//                判断是否需要更新数据 needUpload为0不需要更新
                    WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo);
                    LOGGER.info("before  goto "+charge.getNeedUpload()+" == "+ outChargeNo);
                    LOGGER.info("before  goto " + charge.getNeedUpload() + " == " + outChargeNo);
                    if (charge != null && !("0".equals(charge.getNeedUpload()))) {
                        pay.updateData(outChargeNo, chargeNo, chargeTime, totalAmount, insuranceAmount, selfPayAmount, billNo, miRegisterNo);
                        LOGGER.info("after  goto "+charge.getNeedUpload()+" == "+ outChargeNo);
                        pay.updateData(chargeStatus, formatDate.parse(chargeTime), chargeNo, charge);
                        LOGGER.info("after  goto " + charge.getNeedUpload() + " == " + outChargeNo);
                    }
                    response.getWriter().write("SUCCESS");

+ 2 - 2
patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu.txt

@ -51,8 +51,8 @@
        },
        {
            "type":"view",
            "name":"热量查询",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2frlcx%2fhtml%2fserach-index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
            "name":"妇幼保健",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2ffybj%2fhtml%2fyunjianjihua.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	  ]
   },