
package com.yihu.jw.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.base.wx.WxPayLogDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.dict.WlyyChargeDictDO;
import com.yihu.jw.entity.hospital.httplog.WlyyHttpLogDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.entity.order.BusinessOrderRefundDO;
import com.yihu.jw.hospital.dict.WlyyChargeDictDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.WlyyHttpLogDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.prescription.dao.*;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.order.dao.BusinessOrderRefundDao;
import com.yihu.jw.order.dao.ConsultOrderDao;
import com.yihu.jw.order.pay.wx.WeChatConfig;
import com.yihu.jw.order.pay.ylz.YlzPayService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.sms.dao.BaseSmsTemplateDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.common.XMLUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.WeiXinPayUtils;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.utils.ByteToInputStream;
import com.yihu.jw.utils.YkyySMSService;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.dao.WxPayLogDao;
import com.yihu.jw.wechat.enterprise.EnterpriseService;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * 业务订单
 */
@Service
public class BusinessOrderService extends BaseJpaService<BusinessOrderDO,BusinessOrderDao> {

    private Logger logger = LoggerFactory.getLogger(BusinessOrderService.class);

    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxPayLogDao wxPayLogDao;
    @Autowired
    private BasePatientWechatDao patientWechatDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BusinessOrderRefundDao orderRefundDao;
    @Autowired
    private YkyyService ykyyService;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private ConsultOrderDao consultOrderDao;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private YkyyEntranceService ykyyEntranceService;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private YlzPayService ylzPayService;
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Value("${wechat.flag}")
    private boolean flag;
    @Value("${wechat.id}")
    private String wechatId;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private PrescriptionService prescriptionService;
    @Autowired
    private WlyyChargeDictDao chargeDictDao;
    @Autowired
    private WlyyHttpLogDao wlyyHttpLogDao;
    @Autowired
    private BaseNatAppointmentDao baseNatAppointmentDao;
    @Autowired
    private BaseSmsTemplateDao smsTemplateDao;
    @Autowired
    private YkyySMSService ykyySMSService;
    @Autowired
    private WlyyInspectionDao inspectionDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private HttpClientUtil httpClientUtil;


    /**
     *
     * 处方下单
     * drugType	String	药品类型【1，到院 2、到商城】
     orderId	String	订单Id
     userId	String	用户Id
     Shopping	String	药品列表
     commodityName	String	药品名称
     commodityPrice	String	价格
     purchaseQuantity	String	数量
     DrugUnit	String	单位
     MedicineDoctor	String	医生Id
     [{"commodityName":"","commodityPrice":"","DrugUnit":"","MedicineDoctor":""}]
     * @return
     * @throws Exception
     */
    public List<BusinessOrderDO> savePrescriptionOrder(String code) throws Exception {
        List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(code);
        List<BusinessOrderDO> businessOrderDOS = new ArrayList<>();
        if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
            WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
            BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(wlyyPrescriptionDO.getId());
            if (businessOrderDO==null) {
                businessOrderDO = new BusinessOrderDO();
                businessOrderDO.setCreateTime(new Date());
                businessOrderDO.setUpdateTime(new Date());
                businessOrderDO.setStatus(0);
                businessOrderDO.setOrderNo("HLWYY" + System.currentTimeMillis() + (int) (Math.random() * 900) + 100);
                businessOrderDO.setUploadStatus(0);
                businessOrderDO.setPayType(1);
                businessOrderDO.setRelationCode(code);
                businessOrderDO.setRelationName("处方结算");
                businessOrderDO.setOrderCategory("4");
                businessOrderDO.setOrderType(4);
                businessOrderDO.setDoctor(wlyyPrescriptionDO.getDoctor());
                businessOrderDO.setPatient(outpatientDO.getConsumer());
                businessOrderDO.setPatientName(outpatientDO.getConsumerName());
                BigDecimal b = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getDrugFee()==null?0:wlyyPrescriptionDO.getDrugFee()));
                BigDecimal c = new BigDecimal(String.valueOf(100));
                BigDecimal bc = b.multiply(c);
                BigDecimal dc = new BigDecimal(0);
                //判断检查检验项目是否有金额
                if (wlyyPrescriptionDO.getInspectFee()!=null){
                    BigDecimal d = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getInspectFee()));
                    dc= d.multiply(c);
                }
                businessOrderDO.setPayPrice(bc.doubleValue());
                businessOrderDO.setDescription("处方结算");
                businessOrderDO = businessOrderDao.save(businessOrderDO);
                businessOrderDOS.add(businessOrderDO);
                wlyyPrescriptionDO.setOrderNo(businessOrderDO.getOrderNo());
                wlyyPrescriptionDO.setOrderId(getCode());
                wlyyPrescriptionDO = prescriptionDao.save(wlyyPrescriptionDO);
                JSONArray array = new JSONArray();
                List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(code, 1);
                if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                    WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
                    for (WlyyPrescriptionInfoDO prescriptionInfoDO : wlyyPrescriptionInfoDOS) {
                        JSONObject object = new JSONObject();
                        //{"commodityName":"","commodityPrice":"","DrugUnit":"","MedicineDoctor":""}
                        object.put("commodityName", prescriptionInfoDO.getDrugName());
                        object.put("commodityPrice", prescriptionInfoDO.getPackRetprice());
                        object.put("DrugUnit", prescriptionInfoDO.getPackUnitName());
                        DoctorMappingDO doctorMappingDO = doctorMappingDao.findByDoctor(businessOrderDO.getDoctor());
                        String yktDoctor = "";
                        if (doctorMappingDO != null && StringUtils.isNoneBlank(doctorMappingDO.getMappingCode())) {
                            System.out.println("----------------"+hospitalSysDictDO.getDictValue());
                            if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

                            } else {
                                String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                                JSONObject jsonObject = JSONObject.parseObject(doctorResponse);
                                if (jsonObject.getInteger("code") == 200) {
                                    JSONArray array1 = jsonObject.getJSONArray("data");
                                    if (array1 != null && array1.size() != 0) {
                                        yktDoctor = array1.getJSONObject(0).getString("DOCTORUSERID");
                                    }
                                }
                            }
                        } else {
                            throw new Exception("医生映射表不存在！");
                        }
                        object.put("MedicineDoctor", yktDoctor);
                        array.add(object);
                    }
                    BasePatientDO patientDO = patientDao.findById(businessOrderDO.getPatient());
                    String userId = null;
                    if (patientDO != null) {
                        userId = patientDO.getUserId();
                    }
                    if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

                    } else {
                        String response = ykyyService.addOrder4Jkzl("1", wlyyPrescriptionDO.getOrderId(), businessOrderDO.getOrderNo(), userId, array);
                        if (StringUtils.isNoneBlank(response)) {
                            JSONObject jsonObject = JSONObject.parseObject(response);
                            if (jsonObject.getString("code").equalsIgnoreCase("10000")) {
                                String orderId = jsonObject.getString("orderId");
                                String orderNo = jsonObject.getString("orderNo");
                                businessOrderDO.setYkOrderId(orderId);
                                businessOrderDO.setYkOrderNo(orderNo);
                                businessOrderDO.setUploadStatus(1);
                                businessOrderDao.save(businessOrderDO);
                            }
                        }
                    }
                }
            }else {
                BigDecimal b = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getDrugFee()==null?0:wlyyPrescriptionDO.getDrugFee()));
                BigDecimal c = new BigDecimal(String.valueOf(100));
                BigDecimal bc = b.multiply(c);
                BigDecimal dc = new BigDecimal(0);
                //判断检查检验项目是否有金额
                if (wlyyPrescriptionDO.getInspectFee()!=null){
                    BigDecimal d = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getInspectFee()));
                    dc= d.multiply(c);
                }
                businessOrderDO.setPayPrice(bc.doubleValue());
                businessOrderDao.save(businessOrderDO);
            }
        }
        return businessOrderDOS;
    }

    /**
     * @param businessOrderDO
     * @return
     * @throws Exception
     */
    public BusinessOrderDO saveOrder(BusinessOrderDO businessOrderDO) throws Exception {
        businessOrderDO.setCreateTime(new Date());
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setStatus(0);
        if (StringUtils.isNoneBlank(businessOrderDO.getDoctor())){
            if (businessOrderDO.getOrderType()==3){
                businessOrderDO.setOrderNo("HLWYY3"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            }else {
                businessOrderDO.setOrderNo("HLWYY"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            }

        }else {
            if (businessOrderDO.getOrderType()==3){
                businessOrderDO.setOrderNo("HLWYYQD3"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            }else {
                businessOrderDO.setOrderNo("HLWYYQD"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            }
        }
        businessOrderDO.setUploadStatus(0);
        businessOrderDO.setPayType(1);
        String baseUrl = prescriptionService.findDomainUrlInDict();
        if (businessOrderDO.getOrderCategory().equalsIgnoreCase("1")){
            businessOrderDO.setAppCallbackUrl(baseUrl+"/ims-app-web/#/yk/consult/record?consultCode="+businessOrderDO.getRelationCode()+"&verifyCode=");
            businessOrderDO.setPcCallbackUrl(baseUrl+"/ims-web/#/yk/consult/record?consultCode="+businessOrderDO.getRelationCode()+"&verifyCode=");
        }else {
            businessOrderDO.setAppCallbackUrl(baseUrl+"/ims-app-web/#/yk/consult/record?outpatientId="+businessOrderDO.getRelationCode()+"&verifyCode=");
            businessOrderDO.setPcCallbackUrl(baseUrl+"/ims-web/#/yk/consult/record?outpatientId="+businessOrderDO.getRelationCode()+"&verifyCode=");
        }
        List<WlyyHospitalSysDictDO> hospitalSysDictDOS = hospitalSysDictDao.findByDictName("WX_MONEY");
        if (businessOrderDO!=null&&businessOrderDO.getPayPrice()==null){
            String totalFee = null;
            if (hospitalSysDictDOS!=null&&hospitalSysDictDOS.size()!=0){
                totalFee= hospitalSysDictDOS.get(0).getDictValue();
            }
            businessOrderDO.setPayPrice(StringUtils.isNoneBlank(totalFee)?Double.parseDouble(totalFee):0.0);
        }
        businessOrderDO = businessOrderDao.save(businessOrderDO);
        String patient = businessOrderDO.getPatient();
        BasePatientDO basePatientDO = patientDao.findById(patient);
        String orderNo = businessOrderDO.getOrderNo();
        String patientId = "";
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
        if (StringUtils.isNoneBlank(basePatientDO.getYktId())){
            patientId = basePatientDO.getYktId();
        }else {
            if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

            } else {
                patientId = ykyyService.registerYkt(basePatientDO.getId());
            }
        }
        String orderAmout = businessOrderDO.getPayPrice()/100+"";
        String description = businessOrderDO.getDescription();
        String state = businessOrderDO.getStatus().toString();
        String orderType =businessOrderDO.getOrderType().toString();
        String payType="2";
        String patientTel = basePatientDO.getMobile();
        DoctorMappingDO doctorMappingDO = null;
        if (StringUtils.isNoneBlank(businessOrderDO.getDoctor())){
            doctorMappingDO = doctorMappingDao.findByDoctor(businessOrderDO.getDoctor());
        }
        String orderCatagrate = businessOrderDO.getOrderCategory();
        String pcCallBack=businessOrderDO.getPcCallbackUrl();
        String appCallBack = businessOrderDO.getAppCallbackUrl();
        String yktDoctor ="";

        if (doctorMappingDO!=null&&StringUtils.isNoneBlank(doctorMappingDO.getMappingCode())){
            if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

            } else {
                String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
                System.out.println("Continue");
                JSONObject jsonObject = JSONObject.parseObject(doctorResponse);
                if (jsonObject.getInteger("code")==200){
                    JSONArray array = jsonObject.getJSONArray("data");
                    if (array!=null&&array.size()!=0){
                        yktDoctor=array.getJSONObject(0).getString("DOCTORUSERID");
                    }else {
                        yktDoctor = "hlwyymrys001";
                    }
                }
            }

        }else {
            /*throw new Exception("医生映射表不存在！");*/
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                yktDoctor="hlwyymrys001";
            }
        }
        String remark = businessOrderDO.getRematk();
        if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

        } else {
            try {
                String response=ykyyService.addYktOrder(orderNo,patientId,orderAmout,remark,state,orderType,yktDoctor,payType,null,patientTel,orderCatagrate,pcCallBack,appCallBack);
                JSONObject object = JSONObject.parseObject(response);
                WlyyHttpLogDO wlyyHttpLogDO = new WlyyHttpLogDO();
                wlyyHttpLogDO.setResponse(response);
                wlyyHttpLogDO.setRequest("orderNo;"+orderNo+";"+"yktDoctor:"+yktDoctor);
                wlyyHttpLogDO.setName("同步眼科通订单接口");
                wlyyHttpLogDO.setCreateTime(new Date());
                wlyyHttpLogDao.save(wlyyHttpLogDO);
                if (object.getInteger("code")==200){
                    businessOrderDO.setUploadStatus(1);
                    businessOrderDao.save(businessOrderDO);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return businessOrderDO;
    }

    /**
     * 创建订单并输出微信JSAPI参数
     * @param businessOrderDO
     * @param wechatId
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveOrderAndPay(BusinessOrderDO businessOrderDO,String wechatId) throws Exception {
        businessOrderDO.setStatus(0);
        businessOrderDO.setCreateTime(new Date());
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setOrderNo("HLWYY"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        businessOrderDO = businessOrderDao.save(businessOrderDO);
        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wechatId,businessOrderDO.getPatient());
        String openId = "";
        if (patientWechatDos!=null&&patientWechatDos.size()!=0){
            openId = patientWechatDos.get(0).getOpenid();
        }
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        String patient = businessOrderDO.getPatient();
        BasePatientDO basePatientDO = patientDao.findById(patient);
        String orderNo = businessOrderDO.getOrderNo();
        String patientId = basePatientDO.getYktId();
        String orderAmout = businessOrderDO.getPayPrice()/100+"";
        String description = businessOrderDO.getDescription();
        String state = businessOrderDO.getStatus().toString();
        String orderType =businessOrderDO.getOrderType().toString();
        String payType="2";
        String patientTel = basePatientDO.getMobile();
        DoctorMappingDO doctorMappingDO = null;
        if (StringUtils.isNoneBlank(businessOrderDO.getDoctor())){
            doctorMappingDO = doctorMappingDao.findByDoctor(businessOrderDO.getDoctor());
        }
        String orderCatagrate = businessOrderDO.getOrderCategory();
        String pcCallBack=businessOrderDO.getPcCallbackUrl();
        String appCallBack = businessOrderDO.getAppCallbackUrl();
        String url = wxWechatDO.getBaseUrl();
        String notifyUrl =url;
        Map<String,Object> map = unifiedorder(wechatId,description,businessOrderDO.getPayPrice().toString(),WeChatConfig.TRADE_TYPE_JSAPI,openId,orderNo,notifyUrl,patient);
        String doctorId = "";
        if (doctorMappingDO!=null){
            doctorId = doctorMappingDO.getMappingCode();
        }else {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                doctorId="hlwyymrys001";
            }
        }
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
        if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

        } else {
            ykyyService.addYktOrder(orderNo,patientId,orderAmout,description,state,orderType,doctorId,payType,null,patientTel,orderCatagrate,pcCallBack,appCallBack);

        }
        return map;
    }

    /**
     * 微信统一下单接口
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> unifiedorder(Map<String,String> par,String appKey) throws Exception {
        String xml = WeiXinPayUtils.getXmlBeforUnifiedorder(par, appKey);
        Map<String, Object> map = WeiXinPayUtils.unifiedorder(xml,true);
        System.out.println("____wxPayResult"+map.get("wxPayResult"));
        //创建日志记录
        createLog(par,xml,map);
        map.remove("wxPayResult");
        return map;
    }

    /**
     * 微信统一退款接口
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public String refund(Map<String,String> par,String appKey) throws Exception {
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("REFUND");
        if(StringUtils.isNoneBlank(hospitalSysDictDO.getImgUrl())){
            //公网域名必须为https
            par.put("notify_url",hospitalSysDictDO.getImgUrl());
        }
        String xml= WeiXinPayUtils.getXmlBeforUnifiedorder(par, appKey);
        logger.info("xml:"+xml);

        return HttpUtil.doRefund("https://api.mch.weixin.qq.com/secapi/pay/refund",xml,hospitalSysDictDO.getDictCode(),hospitalSysDictDO.getDictValue());
    }

    public Map<String, Object> checkApplets(String code,String appid,String appSecret) throws Exception {
        HttpUtils httpUtils = new HttpUtils();
        Map<String, Object> param = new HashedMap();
        param.put("appid", appid);
        param.put("secret", appSecret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");

        HttpResponse response = httpUtils.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        org.json.JSONObject rs = new org.json.JSONObject(response.getContent());
        Map<String, Object> res = new HashedMap();
        logger.info("checkApplets:"+response.getContent());
        if (rs.has("openid")){
            res.put("openid", rs.getString("openid"));
            res.put("sessionKey", rs.getString("session_key"));
        }
        return res;
    }
    public Map<String,Object> selectOrderByRelationCode(String relationCode,String tradeType,String wechatId,boolean payFlag,String appletCode) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        if (NumberUtils.isDigits(relationCode) ){
            BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(Integer.valueOf(relationCode));
            if (baseNatAppointmentDO!=null&&"-1".equalsIgnoreCase(baseNatAppointmentDO.getIsSuccess())){
                throw new Exception("订单已取消");
            }
            if (businessOrderDO!=null&&businessOrderDO.getStatus()==1){
                throw new Exception("订单已支付");
            }
        }
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(relationCode);
        if (wlyyOutpatientDO!=null){
            if ("-1".equalsIgnoreCase(wlyyOutpatientDO.getStatus())){
                throw new Exception("订单已取消");
            }
            if (1==wlyyOutpatientDO.getPayStatus()){
                throw new Exception("订单已支付");
            }
            if (businessOrderDO!=null&&businessOrderDO.getStatus()==1){
                throw new Exception("订单已支付");
            }
        }

        String body = businessOrderDO.getDescription();
        String totalFee = businessOrderDO.getPayPrice().intValue()+"";
        String patient = businessOrderDO.getPatient();
        String openid = "";
        if (StringUtils.isNotBlank(appletCode)){
            logger.info("appletCode不为空"+appletCode);
            Map<String,Object> objectMap = checkApplets(appletCode,wxWechatDO.getApplets(),wxWechatDO.getAppletsSecret());
            if (objectMap!=null){
                openid = objectMap.get("openid").toString();
                logger.info("appletCode"+appletCode);
                logger.info("openid"+openid);
            }
        }else {
            logger.info("appletCode为空"+appletCode);
            if (StringUtils.isNoneBlank(patient)){
                List<BasePatientWechatDo> patientWechatDo = patientWechatDao.findByWechatIdAndPatientId(wechatId,patient);
                if (patientWechatDo!=null&&patientWechatDo.size()!=0){
                    openid = patientWechatDo.get(0).getOpenid();
                }
            }
        }
        if (businessOrderDO.getOrderNo()!=null&&businessOrderDO.getOrderNo().contains("HLWYYQD")){
            businessOrderDO.setOrderNo("HLWYYQD"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        }else {
            businessOrderDO.setOrderNo("HLWYY"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        }
        businessOrderDao.save(businessOrderDO);
        String ourTradeNo = businessOrderDO.getOrderNo();
        if (!StringUtils.isNoneBlank(tradeType)){
            tradeType=WeChatConfig.TRADE_TYPE_JSAPI;
        }
        String url = wxWechatDO.getBaseUrl();
        String notifyUrl =url;
        Map<String,Object> map = new HashedMap();
        if (payFlag){
            map = unifiedorder(wechatId,body,totalFee,tradeType,openid,ourTradeNo,notifyUrl,patient);
        }else {
            updatePayStatusByRelation(relationCode,wechatId);
        }
        return map;
    }

    /**
     * 微信下单
     * @param wechatId
     * @param body
     * @param totalFee
     * @param tradeType
     * @param openId
     * @param ourTradeNo
     * @param notifyUrl
     * @return
     * @throws Exception
     */
    public  Map<String,Object> unifiedorder(String wechatId,String body,String totalFee,String tradeType,String openId,String ourTradeNo,String notifyUrl,String code) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        if(!StringUtils.isNoneBlank(notifyUrl)){
            throw new Exception("notifyUrl is null :the notifyUrl is "+notifyUrl);
        }
        if(!StringUtils.isNoneBlank(body)){
            throw new Exception("body is null :the body is "+body);
        }
        if(!StringUtils.isNoneBlank(tradeType)){
            throw new Exception("tradeType is null :the tradeType is "+tradeType);
        }
        if (tradeType.equalsIgnoreCase("JSAPI")){
            if(!StringUtils.isNoneBlank(openId)){
                throw new Exception("openId is null :the openId is "+openId);
            }
        }
        if(!StringUtils.isNoneBlank(ourTradeNo)){
            throw new Exception("ourTradeNo is null :the ourTradeNo is "+ourTradeNo);
        }
        HashMap<String, String> map = new HashMap<>();
        if (tradeType.equalsIgnoreCase("APPLETS")){
            map.put("appid",wxWechatDO.getApplets());
            map.put("trade_type", "JSAPI");
        }else {
            map.put("appid",wxWechatDO.getAppId());
            map.put("trade_type", tradeType);
        }

        map.put("mch_id",wxWechatDO.getMchId());
        map.put("body",body);
        map.put("out_trade_no",ourTradeNo);
        map.put("fee_type","CNY");
        map.put("total_fee",totalFee);
        map.put("spbill_create_ip",getServerIp());
        map.put("notify_url",notifyUrl);

        if (tradeType.equalsIgnoreCase("JSAPI")){
            map.put("openid", openId);
        }
        if (tradeType.equalsIgnoreCase("APPLETS")){
            /*BasePatientDO patientDO = patientDao.findById(code);
            if (patientDO!=null){
                map.put("openid",patientDO.getOpenid());
            }*/
            map.put("openid", openId);
        }
        String wapUrl = "";
        String wapName = "";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            wapUrl = "https://www1.yanketong.com";
            wapName = "厦门大学附中厦门眼科中心";
        }
        if (tradeType.equalsIgnoreCase("MWEB")){
            System.out.println("------进入h5支付-----");
            JSONObject jsonObject = new JSONObject();
            JSONObject object = new JSONObject();
            object.put("type","Wap");
            object.put("wap_url",wapUrl);
            object.put("wap_name",wapName);
            jsonObject.put("h5_info",object);
            map.put("scene_info",jsonObject.toJSONString());
        }
      /*  String token_url = "https://api.weixin.qq.com/cgi-bin/token";
        String params = "grant_type=client_credential&appid=" + wxWechatDO.getAppId() + "&secret=" + wxWechatDO.getAppSecret();
        String result = HttpUtil.sendGet(token_url, params);
        JSONObject json = new JSONObject(result);
        if (json.has("access_token")) {
            String token = json.get("access_token").toString();
            String expires_in = json.get("expires_in").toString();
            String openidList_url = "https://api.weixin.qq.com/cgi-bin/user/get";
            String params1 ="access_token="+ token +"&next_openid=";
            String result1 = HttpUtil.sendGet(openidList_url, params1);
            JSONObject json1 = new JSONObject(result1);
        }*/
        logger.info("map:"+map.toString());
        Map<String, Object> pay = unifiedorder(map, wxWechatDO.getAppKey());
        String returnCode = pay.get("return_code").toString();
        String resultCode = pay.get("result_code").toString();
        System.out.println("-----返回结果："+resultCode);
        System.out.println("-----return_code："+returnCode);
        if (returnCode.equalsIgnoreCase("SUCCESS")){
            String appid = pay.get("appid").toString();
            String mchId = pay.get("mch_id").toString();
            String nonceStr = pay.get("nonce_str").toString();
            String prepayId = pay.get("prepay_id").toString();
            String trade = "";
            if ("SUCCESS".equalsIgnoreCase(resultCode)){
                trade = pay.get("trade_type").toString();
                if (trade.equalsIgnoreCase("Native")){
                    Map<String,String> param = new HashedMap();
                    param.put("appId",appid);
                    param.put("package","prepay_id="+prepayId);
                    param.put("nonceStr",nonceStr);
                    param.put("signType","MD5");
                    param.put("timeStamp",getTimeStamp());
                    param = WeiXinPayUtils.getMapAfterUnifiedorder(param,wxWechatDO.getAppKey());
                    InputStream qrcode = QrcodeUtil.createQrcode(pay.get("code_url").toString(),300,"jpg");
                    ByteToInputStream byteToInputStream = new ByteToInputStream();
                    String QRCodeImg = byteToInputStream.getBase64FromInputStream(qrcode);
                    param.put("qrcode","data:image/png;base64,"+ QRCodeImg);
                    pay.put("native",param);
                }//h5支付方法 返回跳转的微信收银台地址
                else if("MWEB".equalsIgnoreCase(trade)){
                    Map<String,String> param = new HashedMap();
                    param.put("appId",appid);
                    param.put("package","prepay_id="+prepayId);
                    param.put("nonceStr",nonceStr);
                    param.put("signType","MD5");
                    param.put("timeStamp",getTimeStamp());
                    param = WeiXinPayUtils.getMapAfterUnifiedorder(param,wxWechatDO.getAppKey());
                    //微信收银台地址
                    String mwebUrl = pay.get("mweb_url").toString();
                    System.out.println("返回的webUrl"+mwebUrl);
                    param.put("mweb_url",mwebUrl);
                    pay.put("MWEB",param);
                }else {
                    Map<String,String> param = new HashedMap();
                    param.put("appId",appid);
                    param.put("package","prepay_id="+prepayId);
                    param.put("nonceStr",nonceStr);
                    param.put("signType","MD5");
                    param.put("timeStamp",getTimeStamp());
                    param = WeiXinPayUtils.getMapAfterUnifiedorder(param,wxWechatDO.getAppKey());
                    pay.put("jsapi",param);
            }
            }else {
                //支付失败返回信息
                Map<String,String> param = new HashedMap();
                param.put("err_code",pay.get("err_code").toString());
                param.put("err_code_des",pay.get("err_code_des").toString());
                pay.put("payFailed",param);
            }
        }else {
            //通信失败返回信息
            Map<String,String> param = new HashedMap();
            param.put("return_code",pay.get("return_code").toString());
            param.put("return_msg",pay.get("return_msg").toString());
            pay.put("connectFailed",param);
        }
        return pay;
    }


    /**
     * 微信退款
     * @param wechatId
     * @param patient
     * @param orderNo
     * @param refundPrice
     * @param description
     * @return
     * @throws Exception
     */
    public Map<String,Object> orderRefund(String wechatId,String patient,String orderNo,Double refundPrice,String description) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if (wxWechatDO==null){
            throw new Exception("this wechatId is null");
        }
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        if (businessOrderDO==null){
            throw new Exception("this orderId not exit");
        }
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("this patient not exit");
        }
        BusinessOrderRefundDO orderRefundDO = orderRefundDao.selectByOrderNo(orderNo);
        if (orderRefundDO==null){
            orderRefundDO = new BusinessOrderRefundDO();
        }
        orderRefundDO.setCreateTime(new Date());
        orderRefundDO.setUpdateTime(new Date());
        orderRefundDO.setStatus(1);
        orderRefundDO.setOrderNo(orderNo);
        orderRefundDO.setOrderPrice(businessOrderDO.getPayPrice());
        orderRefundDO.setRefundPrice(refundPrice);
        orderRefundDO.setAppId(wxWechatDO.getAppId());
        orderRefundDO.setMchId(wxWechatDO.getMchId());
        orderRefundDO.setOutRefundNo("HLWYY"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        orderRefundDO.setPatient(patient);
        orderRefundDO.setPatientName(patientDO.getName());
        orderRefundDO.setRefundDesc(description);
        orderRefundDO = orderRefundDao.save(orderRefundDO);
        Integer orderPrice = orderRefundDO.getOrderPrice().intValue();
        Integer refundPrice1 = orderRefundDO.getRefundPrice().intValue();
        Map<String,Object> map = refund(wechatId,orderRefundDO.getOrderNo(),orderRefundDO.getOutRefundNo(),orderPrice.toString(),refundPrice1.toString(),orderRefundDO.getRefundDesc());
        logger.info("map"+map);
        if (map.get("return_code").toString().equalsIgnoreCase("SUCCESS")){
            orderRefundDO.setStatus(2);
            orderRefundDO.setRefundTime(new Date());
            orderRefundDao.save(orderRefundDO);
            updatePayStatusByRefund(orderNo);
        }
        if (businessOrderDO!=null){
            ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(),"2");
        }
        return map;
    }

    public Map<String,Object> refund(String wechatId,String outTradeNo,String outRefundNo,String totalFee,String refundFee,String descrption) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        if(!StringUtils.isNoneBlank(refundFee)){
            throw new Exception("refundFee is null :the refundFee is "+refundFee);
        }
        if(!StringUtils.isNoneBlank(outRefundNo)){
            throw new Exception("outRefundNo is null :the outRefundNo is "+outRefundNo);
        }
        if(!StringUtils.isNoneBlank(outTradeNo)){
            throw new Exception("outTradeNo is null :the outTradeNo is "+outTradeNo);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",wxWechatDO.getAppId());
        map.put("mch_id",wxWechatDO.getMchId());
        map.put("out_trade_no",outTradeNo);
        map.put("out_refund_no",outRefundNo);
        map.put("refund_fee",refundFee);
        map.put("total_fee",totalFee);
        map.put("refund_desc",descrption);
        logger.info("map:"+map);

        String res = refund(map, wxWechatDO.getAppKey());
        Map<String, Object> refund  =  XMLUtil.xmltoMap(res);
        return refund;
    }

    /**
     * 添加微信支付日志
     * @param map
     * @param orderPar
     * @param orderRes
     */
    public void createLog(Map<String,String> map,String orderPar,Map<String,Object> orderRes){
        System.out.println("添加支付日志开始");
        WxPayLogDO wxPayLogDO = new WxPayLogDO();
        wxPayLogDO.setSeqNo(map.get("out_trade_no"));
        wxPayLogDO.setOpenId(map.get("openid"));
        wxPayLogDO.setType(0);

        wxPayLogDO.setOrderParams(orderPar);
        wxPayLogDO.setOrderResponse(orderRes.get("wxPayResult").toString());
        String return_code = orderRes.get("return_code").toString();
        System.out.println("return_code"+return_code);
        if("SUCCESS".equalsIgnoreCase(return_code)){
            wxPayLogDO.setOrderStatus(1);
        }else{
            wxPayLogDO.setOrderStatus(-1);
        }
        wxPayLogDO.setCreateTime(new Date());
        wxPayLogDO.setPayStatus(0);
        wxPayLogDao.save(wxPayLogDO);
        System.out.println("添加支付日志结束");
    }


    /**
     * 获取服务器ip地址
     *
     * @return
     * @throws UnknownHostException
     */
    public String getServerIp() throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        String hostAddress = address.getHostAddress();//192.168.0.121
        return hostAddress;
    }


    /**
     *  获取当前时间戳
     * @return 当前时间戳字符串
     */
    public static String getTimeStamp(){
        return String.valueOf(System.currentTimeMillis()/1000);
    }

    /**
     * 获取唯一的支付流水号
     */

    public static int Guid=100;

    synchronized public String getGuid() {
        return DateUtil.dateToStr(new Date(),"yyyyMMddHHmmssSSS")+(new Random().nextInt(10));
    }


    /**
     * 微信支付回调
     *
     *
     * @param result
     * @return
     */
    public Map<String,String> getWxPayResultNotify(String result) {
        Map<String,String> rs = new HashedMap();
        Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
        logger.info("回调参数"+wxrs+"==============="+result);
        if("SUCCESS".equals(wxrs.get("return_code").toString())){
            // 我方 订单号+时间差
            String seqNo = wxrs.get("out_trade_no")+"";
            String totalFee=wxrs.get("total_fee")+"";
            // 微信充值流水号
            String wxSeqNo = wxrs.get("transaction_id")+"";
            // 微信分配的终端设备号
            String wxDeviceInfo = wxrs.get("device_info")+"";
            String timeEnd= wxrs.get("time_end")+"";
            //更改业务状态,做日志保存等操作
            BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(seqNo);
            businessOrderDO.setPayTime(DateUtil.strToDate(timeEnd,DateUtil.YYYY_MM_DD_HH_MM_SS));
            WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKTCONTROL");
            WlyyHospitalSysDictDO changeMethod = hospitalSysDictDao.findById("consultPay");
            String changeflag="0";
            String type="";
            if(null!=changeMethod){
                changeflag = changeMethod.getDictValue();
            }
            if (businessOrderDO!=null){
                if (businessOrderDO.getOrderCategory().equalsIgnoreCase("1")){
                    if ("0".equalsIgnoreCase(changeflag)){
                        ConsultDo consultDo = consultOrderDao.findOne(businessOrderDO.getRelationCode());
                        consultDo.setPayStatus(1);
                        consultOrderDao.save(consultDo);
                    }else {
                        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
                        wlyyOutpatientDO.setPayStatus(1);
                        outpatientDao.save(wlyyOutpatientDO);
                        prescriptionService.wxTempalteJPush("outpatient_remind",wlyyOutpatientDO,null,"","","","");
                        if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            type="1";
                        }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            type="17";
                        }
                        if(StringUtils.isNoneBlank(type)){
                            prescriptionService.sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, type, "paySuccess", "");
                        }
                    }

                }else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("2")||businessOrderDO.getOrderCategory().equalsIgnoreCase("3")){
                    WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
                    wlyyOutpatientDO.setPayStatus(1);
                    outpatientDao.save(wlyyOutpatientDO);
                    if (StringUtils.isNoneBlank(wlyyOutpatientDO.getDoctor())){
                        BaseDoctorDO baseDoctorDO= doctorDao.findById(wlyyOutpatientDO.getDoctor());
                        if (baseDoctorDO!=null){
                            ykyySMSService.sendSmsByTempcode("outpatient_remind",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
                            prescriptionService.wxTempalteJPush("outpatient_remind",wlyyOutpatientDO,null,"","","","");
                        }
                        if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            type="9";
                        }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            type="16";
                        }
                        if(StringUtils.isNoneBlank(type)){
                            prescriptionService.sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, type, "paySuccess", "");
                        }
                    }
                }else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("4")){
                    List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(businessOrderDO.getRelationCode());
                    if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
                        WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
                        wlyyPrescriptionDO.setStatus(30);
                        wlyyPrescriptionDO.setPayStatus(1);
                        wlyyPrescriptionDO.setPayTime(new Date());
                        prescriptionDao.save(wlyyPrescriptionDO);
                        /*List<WlyyInspectionDO> inspectionDOList = inspectionDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                        for (WlyyInspectionDO wlyyInspectionDO:inspectionDOList){
                            String updateMsYj01 = "update V_MS_YJ01 t set t.HLWJF=1 where t.yjxh='"+wlyyInspectionDO.getHisCode()+"'";
                            try {
                                ykyyEntranceService.updateHisStatus(updateMsYj01);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }*/
                        prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(),30,1,wlyyPrescriptionDO.getPatientCode(),wlyyPrescriptionDO.getPatientName(),"",new Date());
                        List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1);
                        if (infoDOS!=null&&infoDOS.size()!=0){
                            try {
                                String sql = " update v_ms_dd01 SET FKZT=1 where CFSB = '"+wlyyPrescriptionDO.getRealOrder()+"'";
                                ykyyEntranceService.updateHisStatus(sql);
                                //判断是否是快递如果是则下物流单
                                List<WlyyPrescriptionExpressageDO> expressList=prescriptionExpressageDao.findByOutpatientId(wlyyPrescriptionDO.getOutpatientId());
                                if (null!=expressList&&expressList.size()>0){
                                    WlyyPrescriptionExpressageDO wlyyPrescriptionExpressageDO = expressList.get(0);
                                    if (null!=wlyyPrescriptionExpressageDO&&wlyyPrescriptionExpressageDO.getOneselfPickupFlg()==1){
                                        String condition ="";
                                        if (StringUtils.isNoneBlank(wlyyPrescriptionDO.getAdmNo())){
                                            condition = " t.JZXH = '"+wlyyPrescriptionDO.getAdmNo()+"' and ";
                                        }
                                        String address =wlyyPrescriptionExpressageDO.getProvinceName()+ wlyyPrescriptionExpressageDO.getCityName()+wlyyPrescriptionExpressageDO.getTownName()+wlyyPrescriptionExpressageDO.getStreetName()+wlyyPrescriptionExpressageDO.getAddress();

                                        //同步his写入自取信息
                                        String updatesql = "update v_ms_dd01 t set t.PSFS = 0 ,t.FKZT=1 ,t.SJR= '"+wlyyPrescriptionExpressageDO.getName()+"' ," +
                                                " t.SJRDH = '"+wlyyPrescriptionExpressageDO.getMobile()+"' ,"+
                                                " t.SJRDZ = '"+address+"' ,"+
                                                " t.YFSB = '"+wlyyPrescriptionExpressageDO.getHospitalCode()+"'"+
                                                " where "+condition+" t.CFSB ='"+wlyyPrescriptionDO.getRealOrder()+"'";
                                        ykyyEntranceService.updateHisStatus(updatesql);
                                        logger.info("自取写入更新his");
                                        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
                                        ykyySMSService.sendSmsByTempcode("oneself_pick",wlyyOutpatientDO,wlyyPrescriptionDO,"");

                                    }else {
                                        //向顺丰下单
                                        logger.info("向顺丰快递下单");
                                        String admNo = wlyyPrescriptionDO.getAdmNo();
                                        String realOrder = wlyyPrescriptionDO.getRealOrder();
                                        logger.info("admNo:"+admNo+"-----realorder:"+realOrder);
                                        Object sfResult = new Object();
                                        //sfResult = "{\"mailno\":\"444844980525\",\"mailtype\":\"标准快递\",\"destcode\":\"592\",\"j_name\":\"厦门大学附属中山医院\",\"j_provinceName\":\"福建省\",\"j_cityName\":\"厦门市\",\"j_townName\":\"思明区\",\"j_address\":\"湖滨南路201-209号\",\"j_phone\":\"4003008888\",\"d_name\":\"陈筑城\",\"d_provinceName\":\"福建省\",\"d_cityName\":\"厦门市\",\"d_townName\":\"思明区\",\"d_address\":\"软件园二期望海路55号\",\"d_phone\":\"18205968888\",\"express_type\":11,\"pay_method\":2,\"receive_time\":\"\",\"dispensaryType\":\"1\"}";
                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(realOrder)){
                                            sfResult = prescriptionService.getSFExpressInfoNew(admNo,realOrder,"");
                                        }
                                        String condition ="";
                                        if (StringUtils.isNoneBlank(admNo)){
                                            condition = " t.JZXH = '"+admNo+"' and";
                                        }
                                        if (!"".equals(sfResult)) {
                                            JSONObject json = JSONObject.parseObject(sfResult.toString());
                                            String sfOrder =  json.getString("mailNo");
                                            logger.info("---获取订单号为："+sfOrder);
                                            String address = wlyyPrescriptionExpressageDO.getProvinceName()+wlyyPrescriptionExpressageDO.getCityName()+wlyyPrescriptionExpressageDO.getTownName()+wlyyPrescriptionExpressageDO.getStreetName()+wlyyPrescriptionExpressageDO.getAddress();
                                            String updatesql = "update v_ms_dd01 t set t.PSFS = 1 ,t.FKZT=1 ,t.YFSB = 6 ,t.KDDH ='"+sfOrder+"',t.SJR = '"+wlyyPrescriptionExpressageDO.getName()+"' ," +
                                                    " t.SJRDH = '"+wlyyPrescriptionExpressageDO.getMobile()+"' ,"+
                                                    " t.SJRDZ = '"+address+"'"+
                                                    " where "+condition+" t.CFSB ='"+realOrder+"'";
                                            ykyyEntranceService.updateHisStatus(updatesql);
                                            logger.info("更新his成功");
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        }

                }else if (businessOrderDO!=null&&businessOrderDO.getOrderCategory().equalsIgnoreCase("5")){
                    String price = Integer.parseInt(totalFee)/100+"";
                    if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {

                    } else {
                        if (businessOrderDO.getOrderType()==10){
                            String re = ykyyService.upRecharge4Jkzl(businessOrderDO.getYkOrderNo(), Integer.parseInt(price), 0);
                            logger.info("调用结果="+re);
                        }
                        if (businessOrderDO.getOrderType()==11){
                            String re = ykyyService.upRecharge4Jkzl(businessOrderDO.getYkOrderNo(), Integer.parseInt(price), 1);
                            logger.info("调用结果="+re);
                        }
                    }


                }else if (businessOrderDO!=null&&businessOrderDO.getOrderCategory().equalsIgnoreCase("6")){
                    String price = Integer.parseInt(totalFee)/100+"";
                    BaseNatAppointmentDO baseNatAppointmentDO = baseNatAppointmentDao.findOne(Integer.parseInt(businessOrderDO.getRelationCode()));
                    baseNatAppointmentDO.setPayStatus("1");
                    baseNatAppointmentDao.save(baseNatAppointmentDO);

                    String updatesql = "update V_MS_YJ01 t set t.HLWJF=1 where t.yjxh='"+baseNatAppointmentDO.getRealOrder()+"'";
                    try {
                        ykyyEntranceService.updateHisStatus(updatesql);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //发送核酸支付成功提醒
                    prescriptionService.sendYktemplateMessage(baseNatAppointmentDO.getId(),true);
                }
            }
            if (businessOrderDO!=null&&!businessOrderDO.getOrderCategory().equalsIgnoreCase("5")&&businessOrderDO.getStatus()!=1){
                if (null != hospitalSysDictDO && "0".equalsIgnoreCase(hospitalSysDictDO.getDictValue())) {
                } else {
                    ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(),"1");
                }
            }else {
                ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(),"1");
            }

            businessOrderDO.setStatus(1);
            businessOrderDao.save(businessOrderDO);

            //操作微信日志表记录
            List<WxPayLogDO> wxPayLogDOs = wxPayLogDao.findBySeqNo(seqNo);
            WxPayLogDO wxPayLogDO = wxPayLogDOs.get(0);
            wxPayLogDO.setPayResponse(result);
            wxPayLogDO.setPayStatus(1);
            wxPayLogDO.setPayTime(new Date());
            wxPayLogDO.setPayStatus(1);
            wxPayLogDao.save(wxPayLogDO);
            rs.put("return_code","SUCCESS");
            rs.put("return_msg","OK");
        }else{
            rs.put("return_code","FAIL");
            rs.put("return_msg","OK");
        }
        return rs;
    }



    public String sendDataToYkt(String orderNo){
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        String patient = businessOrderDO.getPatient();
        BasePatientDO basePatientDO = patientDao.findById(patient);
        String patientId = basePatientDO.getYktId();
        String orderAmout = businessOrderDO.getPayPrice()/100+"";
        String description = businessOrderDO.getDescription();
        String state = businessOrderDO.getStatus().toString();
        String orderType =businessOrderDO.getOrderType().toString();
        String payType="2";
        String patientTel = basePatientDO.getMobile();
        DoctorMappingDO doctorMappingDO = null;
        if (StringUtils.isNoneBlank(businessOrderDO.getDoctor())){
            doctorMappingDO = doctorMappingDao.findByDoctor(businessOrderDO.getDoctor());
        }
        String orderCatagrate = businessOrderDO.getOrderCategory();
        String pcCallBack=businessOrderDO.getPcCallbackUrl();
        String appCallBack = businessOrderDO.getAppCallbackUrl();
        String yktDoctor ="";
        if (null!=doctorMappingDO){
            String doctorResponse = ykyyService.getYktDoctor(doctorMappingDO.getMappingCode());
            JSONObject jsonObject = JSONObject.parseObject(doctorResponse);
            if (jsonObject.getInteger("code")==200){
                JSONArray array = jsonObject.getJSONArray("data");
                if (array!=null&&array.size()!=0){
                    yktDoctor=array.getJSONObject(0).getString("DOCTORUSERID");
                }else {
                    if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                        yktDoctor="hlwyymrys001";
                    }
                }
            }
        }else {
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                yktDoctor="hlwyymrys001";
            }
        }

        String response = ykyyService.addYktOrder(orderNo,patientId,orderAmout,description,state,orderType,yktDoctor,payType,null,patientTel,orderCatagrate,pcCallBack,appCallBack);
        return response;
    }

    public String updateStatusToYk(String orderNo){
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        String response = ykyyService.updateYktOrderStatus(orderNo,businessOrderDO.getStatus().toString());
        return response;
    }

    public PrescriptionDao getPrescriptionDao() {
        return prescriptionDao;
    }

    public void setPrescriptionDao(PrescriptionDao prescriptionDao) {
        this.prescriptionDao = prescriptionDao;
    }


    /**
     *
     * 易联众统一支付
     *
     * @param relationCode
     * @param relationName
     * @param orderCategory 1专家咨询2复诊4处方
     * @param remark
     * @param patient
     * @param patientName
     * @param doctor
     * @return
     */
    public BusinessOrderDO recharge(String relationCode,String relationName,String orderCategory,String remark,String patient,String patientName,String doctor,Double payPrice){
        logger.info("参数========="+relationCode+"=="+orderCategory+"=="+patient+"=="+doctor+"==="+payPrice);
        BusinessOrderDO businessOrderDO = new BusinessOrderDO();
        if (orderCategory.equalsIgnoreCase("4")){
             businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
             if (businessOrderDO==null){
                 businessOrderDO = new BusinessOrderDO();
             }
        }
        System.out.println(relationCode+"----"+relationName+"----"+orderCategory+"----"+remark+"----"+patient+"----"+patientName+"----"+doctor+"----"+payPrice+"----");
        businessOrderDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        businessOrderDO.setCreateTime(new Date());
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setUploadStatus(0);
        businessOrderDO.setRelationCode(relationCode);
        businessOrderDO.setRelationName(relationName);
        businessOrderDO.setOrderCategory(orderCategory);
        businessOrderDO.setOrderType(1);
        businessOrderDO.setRematk(remark);
        businessOrderDO.setPatient(patient);
        businessOrderDO.setPatientName(patientName);
        businessOrderDO.setPayType(3);
        businessOrderDO.setStatus(0);
        businessOrderDO.setPayPrice(payPrice);
        businessOrderDO.setDoctor(doctor);
        businessOrderDO = businessOrderDao.save(businessOrderDO);
        return businessOrderDO;
    }


    /**
     * 调取支付参数
     *
     *
     * @param code
     * @param depositType WX_MIN 微信小程序,WX_PUB 微信公众号 ,ALI_WAP 支付宝生活号 WX_QR pc扫码，ALI_QR支付宝扫码
     * @param wechatId
     * @return
     * @throws Exception
     */
    public String reChargeJSON(String code,String depositType,String wechatId) throws Exception {
        String response = null;
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        WlyyHospitalSysDictDO hospitalSysDictDO =hospitalSysDictDao.findById("YLZ_NOTIFY_URL");
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(code);
        if (businessOrderDO!=null){
            BasePatientDO patientDO = patientDao.findById(businessOrderDO.getPatient());
            String idcard = "";
            String ssc = "";
            if (patientDO!=null){
                idcard = patientDO.getIdcard();
            }
            String openId = "";
            List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wechatId,businessOrderDO.getPatient());
            if (patientWechatDos!=null&&patientWechatDos.size()!=0){
                BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
                openId = patientWechatDo.getOpenid();
            }
            String price = businessOrderDO.getPayPrice().toString();
            businessOrderDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            String notifyUrl = hospitalSysDictDO.getDictCode();
            response = ylzPayService.rechargeConsume("123456",businessOrderDO.getPatientName(),"01",ssc,"01",idcard,depositType,
                    price,price,businessOrderDO.getOrderNo(),idcard,"0",businessOrderDO.getPatientName(),businessOrderDO.getRematk(),openId,notifyUrl,notifyUrl,null);
            if (depositType.equalsIgnoreCase("WX_QR")){
                JSONObject object = JSONObject.parseObject(response);
                if (object!=null){
                    JSONObject jsonObject = object.getJSONObject("param");
                    if (object.getString("respCode").equalsIgnoreCase("000000")){
                        InputStream qrcode = QrcodeUtil.createQrcode(jsonObject.getString("qrcode"),300,"jpg");
                        ByteToInputStream byteToInputStream = new ByteToInputStream();
                        String QRCodeImg = byteToInputStream.getBase64FromInputStream(qrcode);
                        jsonObject.put("qrcodeUrl","data:image/png;base64,"+ QRCodeImg);
                        String traceNo = jsonObject.getString("traceNo");
                        businessOrderDO.setTraceNo(traceNo);
                        businessOrderDao.save(businessOrderDO);
                    }
                    response = object.toJSONString();
                }

            }
        }else {
            return "找不到订单!";
        }
        return response;
    }


    /**
     * 调取支付参数
     *
     *
     * @param code
     * @param depositType WX_MIN 微信小程序,WX_PUB 微信公众号 ,ALI_WAP 支付宝生活号 WX_QR pc扫码，ALI_QR支付宝扫码
     * @param wechatId
     * @return
     * @throws Exception
     */
    public String prescriptionPay(String code,String depositType,String wechatId) throws Exception {

        String response = null;
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        WlyyHospitalSysDictDO hospitalSysDictDO =hospitalSysDictDao.findById("YLZ_NOTIFY_URL");
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(code);
        if (businessOrderDO!=null){
            BasePatientDO patientDO = patientDao.findById(businessOrderDO.getPatient());
            String idcard = "";
            String ssc = "";
            if (patientDO!=null){
                idcard = patientDO.getIdcard();
            }
            String openId = "";
            List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wechatId,businessOrderDO.getPatient());
            if (patientWechatDos!=null&&patientWechatDos.size()!=0){
                BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
                openId = patientWechatDo.getOpenid();
            }
            String price = businessOrderDO.getPayPrice().toString();
            businessOrderDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            String notifyUrl = hospitalSysDictDO.getDictCode();
            response = ylzPayService.rechargeConsume("123456",businessOrderDO.getPatientName(),"01",ssc,"01",idcard,depositType,
                    price,price,businessOrderDO.getOrderNo(),idcard,"0",businessOrderDO.getPatientName(),businessOrderDO.getRematk(),openId,notifyUrl,notifyUrl,null);
            if (depositType.equalsIgnoreCase("WX_QR")){
                JSONObject object = JSONObject.parseObject(response);
                if (object!=null){
                    JSONObject jsonObject = object.getJSONObject("param");
                    if (object.getString("respCode").equalsIgnoreCase("000000")){
                        InputStream qrcode = QrcodeUtil.createQrcode(jsonObject.getString("qrcode"),300,"jpg");
                        ByteToInputStream byteToInputStream = new ByteToInputStream();
                        String QRCodeImg = byteToInputStream.getBase64FromInputStream(qrcode);
                        jsonObject.put("qrcodeUrl","data:image/png;base64,"+ QRCodeImg);
                        String traceNo = jsonObject.getString("traceNo");
                        businessOrderDO.setTraceNo(traceNo);
                        businessOrderDao.save(businessOrderDO);
                    }
                    response = object.toJSONString();
                }

            }
        }else {
            return "找不到订单!";
        }
        return response;
    }



    public BusinessOrderDO selectStatus(String relationCode){
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        return businessOrderDO;
    }
    public BusinessOrderDO selectStatusById(Integer id){
        BusinessOrderDO businessOrderDO = businessOrderDao.findOne(id);
        return businessOrderDO;
    }

    public BaseNatAppointmentDO selectById(Integer relationCode){
        return  baseNatAppointmentDao.findOne(relationCode);
    }


    public List<BusinessOrderDO> selectListStatus(String relationCode){
        List<BusinessOrderDO> businessOrderDOList = businessOrderDao.selectListByRelationCode(relationCode);
        return businessOrderDOList;
    }



    /**
     * 易联众退款
     * @param wechatId
     * @param patient
     * @param orderNo
     * @param refundPrice
     * @param description
     * @return
     * @throws Exception
     */
    public Map<String,Object> ylzOrderRefund(String wechatId,String patient,String orderNo,Double refundPrice,String description) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if (wxWechatDO==null){
            throw new Exception("this wechatId is null");
        }
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        if (businessOrderDO==null){
            throw new Exception("this orderId not exit");
        }
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("this patient not exit");
        }
        BusinessOrderRefundDO orderRefundDO = new BusinessOrderRefundDO();
        orderRefundDO = orderRefundDao.selectByOrderNo(orderNo);
        if (orderRefundDO==null){
            orderRefundDO = new BusinessOrderRefundDO();
        }
        orderRefundDO.setCreateTime(new Date());
        orderRefundDO.setUpdateTime(new Date());
        orderRefundDO.setStatus(1);
        orderRefundDO.setOrderNo(orderNo);
        orderRefundDO.setOrderPrice(businessOrderDO.getPayPrice());
        orderRefundDO.setRefundPrice(refundPrice);
        orderRefundDO.setAppId(wxWechatDO.getAppId());
        orderRefundDO.setMchId(wxWechatDO.getMchId());
        orderRefundDO.setOutRefundNo("HLWYY"+businessOrderDO.getOrderCategory()+System.currentTimeMillis());
        orderRefundDO.setPatient(patient);
        orderRefundDO.setPatientName(patientDO.getName());
        orderRefundDO.setRefundDesc(description);
        orderRefundDO = orderRefundDao.save(orderRefundDO);
        String map = ylzPayService.refund(patientDO.getIdcard(),"123456",patientDO.getName(),"01",patientDO.getIdcard(),"01",orderRefundDO.getRefundPrice().toString(),"1",orderRefundDO.getOrderNo(),orderRefundDO.getOutRefundNo(),patientDO.getIdcard());
        JSONObject object = JSONObject.parseObject(map);
        if (object.get("respCode").toString().equalsIgnoreCase("000000")){
            orderRefundDO.setStatus(2);
            orderRefundDO.setRefundTime(new Date());
            orderRefundDao.save(orderRefundDO);
            updatePayStatusByRefund(orderNo);
        }
        return object;



    }


    /**
     * 易联众查询交易订单
     *
     * @param orderNo
     * @param tradeType
     * @return
     */
    public JSONObject tradeQuery(String orderNo,String tradeType){
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        String response = ylzPayService.tradeQuery(null,null,businessOrderDO.getPatientName(),orderNo,tradeType,businessOrderDO.getRematk());
        JSONObject object = JSONObject.parseObject(response);
        return object;
    }


    /**
     *  退款修改状态
     * @param orderNo
     * @return
     */
    public BusinessOrderDO updatePayStatusByRefund(String orderNo) throws Exception {
        logger.info("入参："+orderNo);
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        if (businessOrderDO==null){
            throw new Exception("查不到订单！");
        }
        String newPayFlag = "0";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("consultPay");
        if (null!=wlyyHospitalSysDictDO){
            newPayFlag = wlyyHospitalSysDictDO.getDictValue();
        }
        if (businessOrderDO.getOrderCategory().equalsIgnoreCase("1")){
            if ("0".equalsIgnoreCase(newPayFlag)){
                ConsultDo consultDo = consultOrderDao.findOne(businessOrderDO.getRelationCode());
                consultDo.setPayStatus(2);
                consultOrderDao.save(consultDo);
            }else {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
                wlyyOutpatientDO.setPayStatus(2);
                outpatientDao.save(wlyyOutpatientDO);
            }

        }else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("2")||businessOrderDO.getOrderCategory().equalsIgnoreCase("3")){
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
            wlyyOutpatientDO.setPayStatus(2);
            outpatientDao.save(wlyyOutpatientDO);
        }
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setStatus(9);
        businessOrderDao.save(businessOrderDO);
        return businessOrderDO;
    }

    /**
     *
     * @param orderNo
     * @return
     */
    public BusinessOrderDO updatePayStatus(String orderNo) throws Exception {
        logger.info("入参："+orderNo);
        String baseUrl = prescriptionService.findDomainUrlInDict();
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        WlyyHospitalSysDictDO changeMethod = hospitalSysDictDao.findById("consultPay");
        String changeflag="0";
        if(null!=changeMethod){
            changeflag = changeMethod.getDictValue();
        }
        if (businessOrderDO==null){
            throw new Exception("查不到订单！");
        }
        if (businessOrderDO.getOrderCategory().equalsIgnoreCase("1")&&businessOrderDO.getStatus()==0){
            if ("0".equalsIgnoreCase(changeflag)){
                ConsultDo consultDo = consultOrderDao.findOne(businessOrderDO.getRelationCode());
                consultDo.setPayStatus(1);
                consultOrderDao.save(consultDo);
            }else {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
                wlyyOutpatientDO.setPayStatus(1);
                WlyyOutpatientDO outpatientDO = outpatientDao.save(wlyyOutpatientDO);
                //发送企业模板消息给医生
                BasePatientDO patientDO = new BasePatientDO();
                patientDO = patientDao.findById(outpatientDO.getPatient());
                String msg = "";
                String name=outpatientDO.getPatientName();
                String sex = "";
                String age="";
                String date = "";
                String title = "";
                String type="";
                if (patientDO!=null){
                    sex= IdCardUtil.getSexForIdcard(patientDO.getIdcard());
                    age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard())+"";
                }
                if (outpatientDO!=null){
                    if (outpatientDO.getType().equalsIgnoreCase("1")){
                        title = "图文咨询";
                        type="1";
                        msg = name+"（"+sex+" "+age+"岁）向您发起了图文咨询，点击查看";
                    }else if (outpatientDO.getType().equalsIgnoreCase("2")){
                        title = "视频咨询";
                        type="17";
                        date = DateUtil.dateToStrLong(outpatientDO.getRegisterDate());
                        msg = name+"（"+sex+" "+age+"岁）预约了"+date+"的视频咨询，点击查看";
                    }
                }
                if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
                    String url=baseUrl+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("zsyy",outpatientDO.getDoctor(),title,msg,url);
                }else if(wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                    String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",outpatientDO.getDoctor(),title,msg,url);
                }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                    String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",outpatientDO.getDoctor(),title,msg,url);
                }else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")){
                    String url="https://hlwyy.xmhcyy.com/hcyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_hcyy_wx",outpatientDO.getDoctor(),title,msg,url);
                }
                System.out.println("发送企业模板消息成功");
                try {
                    if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                        prescriptionService.sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, type, "paySuccess", "");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("2")||businessOrderDO.getOrderCategory().equalsIgnoreCase("3")||businessOrderDO.getOrderCategory().equalsIgnoreCase("5")){
           WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
           wlyyOutpatientDO.setPayStatus(1);
           WlyyOutpatientDO outpatientDO = outpatientDao.save(wlyyOutpatientDO);
           try {
               if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)&&StringUtils.isNoneBlank(wlyyOutpatientDO.getDoctor())){
                   String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+wlyyOutpatientDO.getId();
                   prescriptionService.sendZsMsgFlow("OL_PAY_SUCCESS",wlyyOutpatientDO.getId(),"",msgUrl,"已支付问诊费");
               }
           }catch (Exception e){
               e.printStackTrace();
           }
           if (businessOrderDO.getStatus()!=null&&businessOrderDO.getStatus()==0){
               //发送企业模板消息给医生
               BasePatientDO patientDO = new BasePatientDO();
               patientDO = patientDao.findById(outpatientDO.getPatient());
               String msg = "";
               String name=outpatientDO.getPatientName();
               String sex = "";
               String age="";
               String date = "";
               String title = "";
               String type="";
               if (patientDO!=null){
                   sex= IdCardUtil.getSexForIdcard(patientDO.getIdcard());
                   age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard())+"";
               }
               if (outpatientDO!=null){
                   if (outpatientDO.getOutpatientType().equalsIgnoreCase("2")){
                       title = "协同复诊";
                       msg = name+"（"+sex+" "+age+"岁）向您发起了协同复诊，点击查看";
                   }else {
                       if (outpatientDO.getType().equalsIgnoreCase("1")){
                           title = "图文复诊";
                           type="9";
                           msg = name+"（"+sex+" "+age+"岁）向您发起了图文复诊，点击查看";
                       }else if (outpatientDO.getType().equalsIgnoreCase("2")){
                           title = "视频复诊";
                           type="16";
                           date = DateUtil.dateToStrLong(outpatientDO.getRegisterDate());
                           msg = name+"（"+sex+" "+age+"岁）预约了"+date+"的视频复诊，点击查看";
                       }
                   }
               }
               if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
                   String url=baseUrl+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                   enterpriseService.sendTWMesByDoctor("zsyy",outpatientDO.getDoctor(),title,msg,url);
               }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                   String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                   enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",outpatientDO.getDoctor(),title,msg,url);
               }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                   String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                   enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",outpatientDO.getDoctor(),title,msg,url);
               }else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")){
                   String url="https://hlwyy.xmhcyy.com/hcyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                   enterpriseService.sendTWMesByDoctor("xm_hcyy_wx",outpatientDO.getDoctor(),title,msg,url);
               }
               prescriptionService.sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(),null, type, "paySuccess", "");
               System.out.println("发送企业模板消息成功");
           }

        } else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("4")) {
           List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(businessOrderDO.getRelationCode());
           if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
               WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
               wlyyPrescriptionDO.setPayStatus(1);
               prescriptionDao.save(wlyyPrescriptionDO);
               prescriptionLogService.addPrescriptionLog(businessOrderDO.getRelationCode(),30,1,businessOrderDO.getPatient(),businessOrderDO.getPatientName(),businessOrderDO.getDescription(),new Date());
               if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)){
                   String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/prescriptionDetail?outpatientId="+wlyyPrescriptionDO.getOutpatientId()+"&id="+wlyyPrescriptionDO.getId();
                   prescriptionService.sendZsMsgFlow("OL_JS_SUCCESS",wlyyPrescriptionDO.getOutpatientId(),wlyyPrescriptionDO.getId(),msgUrl,"结算成功");
               }
           }
        }
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setStatus(1);
        businessOrderDao.save(businessOrderDO);

        return businessOrderDO;
    }


    /**
     *无需支付
     * @param relationCode
     * @return
     */
    public BusinessOrderDO updatePayStatusByRelation(String relationCode,String wxId) throws Exception {
        logger.info("入参："+relationCode);
        logger.info("进入无需支付");
        String baseUrl = prescriptionService.findDomainUrlInDict();
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        WlyyHospitalSysDictDO changeMethod = hospitalSysDictDao.findById("consultPay");
        String changeflag="0";
        if(null!=changeMethod){
            changeflag = changeMethod.getDictValue();
        }
        if (businessOrderDO==null){
            throw new Exception("查不到订单！");
        }
        if (businessOrderDO.getOrderCategory().equalsIgnoreCase("1")&&0==businessOrderDO.getStatus()){
            if ("0".equalsIgnoreCase(changeflag)){
                ConsultDo consultDo = consultOrderDao.findOne(businessOrderDO.getRelationCode());
                consultDo.setPayStatus(1);
                consultOrderDao.save(consultDo);
            }else {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
                wlyyOutpatientDO.setPayStatus(1);
                WlyyOutpatientDO outpatientDO = outpatientDao.save(wlyyOutpatientDO);
                if (businessOrderDO.getStatus()!=null&&businessOrderDO.getStatus()==0){
                    //发送企业模板消息给医生
                    BasePatientDO patientDO = new BasePatientDO();
                    patientDO = patientDao.findById(outpatientDO.getPatient());
                    String msg = "";
                    String name=outpatientDO.getPatientName();
                    String sex = "";
                    String age="";
                    String date = "";
                    String title = "";
                    if (patientDO!=null){
                        sex= IdCardUtil.getSexForIdcard(patientDO.getIdcard());
                        age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard())+"";
                    }
                    if (outpatientDO!=null){
                        if (outpatientDO.getType().equalsIgnoreCase("1")){
                            title = "图文咨询";
                            msg = name+"（"+sex+" "+age+"岁）向您发起了图文咨询，点击查看";
                        }else if (outpatientDO.getType().equalsIgnoreCase("2")){
                            title = "视频咨询";
                            date = DateUtil.dateToStrLong(outpatientDO.getRegisterDate());
                            msg = name+"（"+sex+" "+age+"岁）预约了"+date+"的视频咨询，点击查看";
                        }
                    }
                    if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                        String url=baseUrl+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                        enterpriseService.sendTWMesByDoctor("zsyy",outpatientDO.getDoctor(),title,msg,url);
                    }else if (wxId.equalsIgnoreCase("xm_xzzx_wx")){
                        String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                        enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",outpatientDO.getDoctor(),title,msg,url);
                    }else if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
                        String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                        enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",outpatientDO.getDoctor(),title,msg,url);
                    }else if (wxId.equalsIgnoreCase("xm_hcyy_wx")){
                        String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                        enterpriseService.sendTWMesByDoctor("xm_hcyy_wx",outpatientDO.getDoctor(),title,msg,url);
                    }
                    if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)&&StringUtils.isNoneBlank(wlyyOutpatientDO.getDoctor())){
                        String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+wlyyOutpatientDO.getId();
                        prescriptionService.sendZsMsgFlow("OL_PAY_SUCCESS",wlyyOutpatientDO.getId(),"",msgUrl,"已支付问诊费");
                    }
                    System.out.println("发送企业模板消息成功");
                }
            }
        }else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("2")||businessOrderDO.getOrderCategory().equalsIgnoreCase("3")||businessOrderDO.getOrderCategory().equalsIgnoreCase("5")&&0==businessOrderDO.getStatus()){
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(businessOrderDO.getRelationCode());
            wlyyOutpatientDO.setPayStatus(1);
            WlyyOutpatientDO outpatientDO = outpatientDao.save(wlyyOutpatientDO);
            if (businessOrderDO.getStatus()!=null&&businessOrderDO.getStatus()==0){
                //发送企业模板消息给医生
                BasePatientDO patientDO = new BasePatientDO();
                patientDO = patientDao.findById(outpatientDO.getPatient());
                String msg = "";
                String name=outpatientDO.getPatientName();
                String sex = "";
                String age="";
                String date = "";
                String title = "";

                if (patientDO!=null){
                    sex= IdCardUtil.getSexForIdcard(patientDO.getIdcard());
                    age = IdCardUtil.getAgeForIdcard(patientDO.getIdcard())+"";
                }
                if (outpatientDO!=null){
                    if (outpatientDO.getOutpatientType().equalsIgnoreCase("2")){
                        title = "协同复诊";
                        msg = name+"（"+sex+" "+age+"岁）向您发起了协同复诊，点击查看";
                    }else {
                        if (outpatientDO.getType().equalsIgnoreCase("1")){
                            title = "图文复诊";
                            msg = name+"（"+sex+" "+age+"岁）向您发起了图文复诊，点击查看";
                        }else if (outpatientDO.getType().equalsIgnoreCase("2")){
                            title = "视频复诊";
                            date = DateUtil.dateToStrLong(outpatientDO.getRegisterDate());
                            msg = name+"（"+sex+" "+age+"岁）预约了"+date+"的视频复诊，点击查看";
                        }
                    }
                }
                if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                    logger.info("进入无需支付zs"+relationCode+"=="+wxId);
                    String url=baseUrl+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("zsyy",outpatientDO.getDoctor(),title,msg,url);
                }else if (wxId.equalsIgnoreCase("xm_xzzx_wx")){
                    String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",outpatientDO.getDoctor(),title,msg,url);
                }else if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
                    String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",outpatientDO.getDoctor(),title,msg,url);
                }else if (wxId.equalsIgnoreCase("xm_hcyy_wx")){
                    String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+outpatientDO.getDescription()+"&type=3&id="+outpatientDO.getId();
                    enterpriseService.sendTWMesByDoctor("xm_hcyy_wx",outpatientDO.getDoctor(),title,msg,url);
                }
                if ("xm_zsyy_wx".equalsIgnoreCase(wechatId)&&StringUtils.isNoneBlank(wlyyOutpatientDO.getDoctor())){
                    String msgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+wlyyOutpatientDO.getId();
                    prescriptionService.sendZsMsgFlow("OL_PAY_SUCCESS",wlyyOutpatientDO.getId(),"",msgUrl,"已支付问诊费");
                }
                System.out.println("发送企业模板消息成功");
            }
        } else if (businessOrderDO.getOrderCategory().equalsIgnoreCase("4")) {
            List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findById(businessOrderDO.getRelationCode());
            if (wlyyPrescriptionDOS!=null&&wlyyPrescriptionDOS.size()!=0){
                WlyyPrescriptionDO wlyyPrescriptionDO = wlyyPrescriptionDOS.get(0);
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setStatus(30);
                prescriptionDao.save(wlyyPrescriptionDO);
                prescriptionLogService.addPrescriptionLog(businessOrderDO.getRelationCode(),30,1,businessOrderDO.getPatient(),businessOrderDO.getPatientName(),businessOrderDO.getDescription(),new Date());
            }
        }
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setStatus(1);
        businessOrderDao.save(businessOrderDO);
        return businessOrderDO;
    }


    public JSONObject selectOrderTime(String relationCode){
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("PAY_TIME");
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        Date createDate = businessOrderDO.getCreateTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createDate);
        if (businessOrderDO.getOrderCategory().equalsIgnoreCase("4")){
            calendar.add(Calendar.MINUTE,Integer.parseInt(wlyyHospitalSysDictDO.getPyCode()));
        }else {
            calendar.add(Calendar.MINUTE,Integer.parseInt(wlyyHospitalSysDictDO.getDictCode()));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(calendar.getTime());
        JSONObject object = new JSONObject();
        object.put("endTime",time);
        object.put("createTime",businessOrderDO.getCreateTime());
        return object;
    }


    /**
     * 预交金支付
     * @param code
     * @param depositType
     * @param wechatId
     * @return
     * @throws Exception
     */
    public String ylzRechargeJson(String code,String depositType,String wechatId,String cardType,String cardNo,boolean demoFlag) throws Exception {
        String response = null;
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(wxWechatDO==null){
            throw new Exception("can't find wechat:the wxId is "+wechatId);
        }
        WlyyHospitalSysDictDO hospitalSysDictDO =hospitalSysDictDao.findById("YLZ_NOTIFY_URL");
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(code);
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(code);
        if (businessOrderDO!=null){
            BasePatientDO patientDO = patientDao.findById(businessOrderDO.getPatient());
            String idcard = "";
            if (patientDO!=null){
                idcard = patientDO.getIdcard();
            }
            logger.info("开始1"+idcard);
            String openId = "";
            Double doctorFee = 0.0;
            if (StringUtils.isNoneBlank(businessOrderDO.getDoctor())){
                BaseDoctorDO doctorDO = doctorDao.findById(businessOrderDO.getDoctor());
                String fee = null;
                if (wechatId.equalsIgnoreCase("xm_zsyy_wx")||wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                    if (wlyyOutpatientDO!=null){
                        if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getTwfzChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else if ("1".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getSpfzChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getTwzxChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getSpzxChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getXtfzChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else if ("3".equalsIgnoreCase(wlyyOutpatientDO.getOutpatientType())&&"3".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getJyzxChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }else {
                            WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeTypeAndDeptTypeCode(doctorDO.getChargeType(),"6");
                            fee = chargeDictDO.getReqFee()+"";
                        }
                    }

                }else {
                    WlyyChargeDictDO chargeDictDO = chargeDictDao.findByChargeType(doctorDO.getChargeType());
                    fee = chargeDictDO.getReqFee()+"";
                }
                if (!StringUtils.isNoneBlank(fee)){
                    throw new Exception("医生费用为空");
                }
                doctorFee= Double.parseDouble(fee);
            }else {
                WlyyHospitalSysDictDO wlyyHospitalSysDictDO =hospitalSysDictDao.findById("WX_MONEY");
                doctorFee = Double.parseDouble(wlyyHospitalSysDictDO.getDictValue());
            }

            WlyyHospitalSysDictDO wlyyHospitalSysDictDO =hospitalSysDictDao.findById("YLZ_YE");
            if (wlyyHospitalSysDictDO!=null&&wlyyHospitalSysDictDO.getDictValue().equalsIgnoreCase("0")){
                businessOrderDO.setPayPrice(doctorFee);
            }else {
                if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
                    net.sf.json.JSONObject object1 = entranceService.qutpatientBalance(cardNo, demoFlag);
                    Double cardFee = object1.getDouble("ZHYE");
                    BigDecimal b = new BigDecimal(String.valueOf(cardFee));
                    BigDecimal c = new BigDecimal(String.valueOf(doctorFee));
                    BigDecimal balance = c.subtract(b);
                    businessOrderDO.setPayPrice(balance.doubleValue());
                }else if(wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                    JSONObject object = xzzxEntranceService.selectCardInfo(cardNo);
                    Double cardFee = object.getDouble("ZHYE");
                    BigDecimal b = new BigDecimal(String.valueOf(cardFee));
                    BigDecimal c = new BigDecimal(String.valueOf(doctorFee));
                    BigDecimal balance = c.subtract(b);
                    businessOrderDO.setPayPrice(balance.doubleValue());
                }

            }
            businessOrderDO.setPayType(4);
            businessOrderDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
            businessOrderDao.save(businessOrderDO);
            List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wechatId,businessOrderDO.getPatient());
            if (patientWechatDos!=null&&patientWechatDos.size()!=0){
                BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
                openId = patientWechatDo.getOpenid();
            }
            String price = businessOrderDO.getPayPrice().toString();
            String notifyUrl = hospitalSysDictDO.getDictCode();
            String operatorId =null;
            String operatorName = null;
            if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
                operatorId = "123456";
                operatorName =businessOrderDO.getPatientName();
            }else if(wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                operatorId = "hlwyy";
                operatorName = "互联网医院";
            }
            response = ylzPayService.recharge(operatorId,operatorName,cardType,"01",cardNo,idcard,depositType,price,businessOrderDO.getOrderNo(),openId,patientDO.getName(),notifyUrl);
            if (depositType.equalsIgnoreCase("WX_QR")){
                JSONObject object = JSONObject.parseObject(response);
                if (object!=null){
                    JSONObject jsonObject = object.getJSONObject("param");
                    if (object.getString("respCode").equalsIgnoreCase("000000")){
                        InputStream qrcode = QrcodeUtil.createQrcode(jsonObject.getString("qrcode"),300,"jpg");
                        ByteToInputStream byteToInputStream = new ByteToInputStream();
                        String QRCodeImg = byteToInputStream.getBase64FromInputStream(qrcode);
                        jsonObject.put("qrcodeUrl","data:image/png;base64,"+ QRCodeImg);
                        String traceNo = jsonObject.getString("traceNo");
                        businessOrderDO.setTraceNo(traceNo);
                        businessOrderDao.save(businessOrderDO);
                    }
                    response = object.toJSONString();
                }

            }
        }else {
            return "找不到订单!";
        }
        return response;
    }


    /**
     * 咨询退费
     * @param consult
     * @return
     */
    public BusinessOrderDO consultRefund(String consult,String wxId) throws Exception {
        String base = hospitalSysDictDao.findByDictName("imData").get(0).getDictCode();
        String sql ="select id as \"id\",reply as \"reply\" from "+base+".topics where id='"+consult+"' AND (reply=0 OR reply IS NULL OR reply <>'')";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        logger.info("maplist"+mapList);
        if (mapList!=null&&mapList.size()!=0){
            BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(consult);
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
                this.orderRefund(wxId,businessOrderDO.getPatient(),businessOrderDO.getOrderNo(),businessOrderDO.getPayPrice(),businessOrderDO.getDescription());
                //眼科接诊时更新眼科通状态
                if (!flag){
                    if (businessOrderDO!=null){
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(),"7");
                    }
                }
            }else if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
/*
                this.ylzOrderRefund(wxId,businessOrderDO.getPatient(),businessOrderDO.getOrderNo(),businessOrderDO.getPayPrice(),businessOrderDO.getDescription());
*/
            }
            return businessOrderDO;
        }
        return null;
    }


    /**
     * 眼科通app支付
     * @param relationCode
     * @return
     * @throws UnknownHostException
     */
    public String yktAppPayJson(String relationCode) throws UnknownHostException {
        String serverIp = getServerIp();
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("YKT_NOTIFY_URL");
        String url = hospitalSysDictDO.getDictCode();
        String notifyUrl =url;
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(relationCode);
        businessOrderDO.setPayType(5);
        businessOrderDao.save(businessOrderDO);
        String totalFee =(int)(businessOrderDO.getPayPrice()*100)+"";
        WlyyHospitalSysDictDO hospitalSysD2ictDO = hospitalSysDictDao.findById("YKTCONTROL");
        if (null != hospitalSysD2ictDO && "0".equalsIgnoreCase(hospitalSysD2ictDO.getDictValue())) {
            return null;
        } else {
            return ykyyService.getPayCDATA4Jkzl(businessOrderDO.getRematk(),businessOrderDO.getOrderNo(),totalFee,serverIp,notifyUrl);

        }
    }
    public MixEnvelop findYktCardCharge(String startTime, String endTime, String orderNo, String yktOrderNo, String patientName
                                                    , String idCard, String medicard,Integer status, Integer page, Integer pageSize,String orderType,String orderCategory){
        String sql = " select t.id as \"id\"," +
                " t.patient as \"patient\","+
                " t.patient_name as \"patientName\","+
                " t.order_no as \"orderNo\","+
                " t.order_type as \"orderType\","+
                " t.relation_code as \"relationCode\","+
                " t.relation_name as \"relationName\","+
                " t.description as \"description\","+
                " t.pay_type as \"payType\","+
                " t.pay_price as \"payPrice\","+
                " t.status as \"status\","+
                " t.pay_time as \"payTime\","+
                " t.upload_status as \"uploadStatus\","+
                " t.create_time as \"createTime\","+
                " t.remark as \"remark\","+
                " t.yk_order_no as \"ykOrderNo\","+
                " t.yk_order_id as \"ykOrderId\","+
                " b.idcard as \"idcard\", "+
                " b.mobile as \"mobile\", "+
                " case t.order_category when '2' then '2' when '3' then '2' else t.order_category end  as \"orderCategory\" "+
                " from base_business_order_pay t" +
                " left join base_patient b on t.patient = b.id  where 1=1  ";
        if (StringUtils.isNoneBlank(startTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time > '" + startTime + "'";
                }else {
                    sql+=" and t.create_time > to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time > '" + startTime + "'";
            }
        }
        if (StringUtils.isNoneBlank(endTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time <= '" + endTime + "'";
                }else {
                    sql+=" and t.create_time <= to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time <= '" + endTime + "'";
            }
        }
        if (StringUtils.isNoneBlank(orderNo)){
            sql+=" and t.order_no like '%"+orderNo+"%'";
        }
        if (StringUtils.isNoneBlank(yktOrderNo)){
            sql+=" and t.yk_order_no like '%"+yktOrderNo+"%'";
        }
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name  like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(idCard)){
            sql+=" and b.idcard like '%"+idCard+"%'";
        }
        if (StringUtils.isNoneBlank(medicard)){
            sql+=" and t.relation_code like '%"+medicard+"%'";
        }
        if (status!=null){
            sql+=" and t.status ="+status+"";
        }

        if (StringUtils.isNoneBlank(orderType)){
            sql+=" and t.order_type ="+orderType+"";
        }

        if (StringUtils.isNoneBlank(orderCategory)){
            if (orderCategory.equalsIgnoreCase("2")){
                sql+=" and t.order_category IN ('2','3') ";
            }
            sql+=" and t.order_category = '"+orderCategory+"'  ";
        }

        sql+=" order by t.create_time desc ";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        for (Map<String,Object> map:list){
            if (map.get("orderCategory")!=null){
                String orderCategoryFlag = map.get("orderCategory").toString();
                if (!orderCategoryFlag.equalsIgnoreCase("5")){
                    Double price = Double.parseDouble(map.get("payPrice").toString());
                    Double prie = price/100;
                    logger.info("price"+prie);
                    map.put("payPrice",prie);
                }
            }
        }
        /*for (Map<String,Object> map:list){
            if (map.get("createTime")!=null){
                map.put("createTime",);
            }
        }*/
        List<Map<String,Object>> listCount  = hibenateUtils.createSQLQuery(sql);
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
        return mixEnvelop;
    }



    public MixEnvelop pushYktCardCharge(String startTime, String endTime, String orderNo, String yktOrderNo, String patientName
            , String idCard, String medicard,Integer status, Integer page, Integer pageSize,String orderType,String orderCategory){
        String sql = "SELECT\n" +
                "\tt.id AS \"id\",\n" +
                "\tt.patient AS \"patient\",\n" +
                "\tt.patient_name AS \"patientName\",\n" +
                "\tt.order_no AS \"orderNo\",\n" +
                "\tt.order_type AS \"orderType\",\n" +
                "\tt.relation_code AS \"relationCode\",\n" +
                "\tt.relation_name AS \"relationName\",\n" +
                "\tt.description AS \"description\",\n" +
                "\tt.pay_type AS \"payType\",\n" +
                "\tt.pay_price AS \"payPrice\",\n" +
                "\tt.create_time AS \"payTime\",\n" +
                "\tt.upload_status AS \"uploadStatus\",\n" +
                "\tt.create_time AS \"createTime\",\n" +
                "\tt.remark AS \"remark\",\n" +
                "\tt.relation_code AS \"medicard\",\n" +
                "\tt.yk_order_no AS \"ykOrderNo\",\n" +
                "\tt.yk_order_id AS \"ykOrderId\",\n" +
                "\tb.idcard AS \"idcard\",\n" +
                "\tb.mobile AS \"mobile\",\n" +
                "\tt. STATUS AS \"status\",\n" +
                "\tt.order_category AS \"orderCategory\"\n" +
                "FROM\n" +
                "\tbase_business_order_pay t\n" +
                "LEFT JOIN base_patient b ON t.patient = b.id\n" +
                "WHERE\n" +
                "\t1 = 1";
        if (StringUtils.isNoneBlank(startTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time > '" + startTime + "'";
                }else {
                    sql+=" and t.create_time > to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time > '" + startTime + "'";
            }
        }
        if (StringUtils.isNoneBlank(endTime)){
            if("xm_ykyy_wx".equals(wechatId)){
                if (flag){
                    sql+=" and t.create_time <= '" + endTime + "'";
                }else {
                    sql+=" and t.create_time <= to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss') ";
                }
            }else{
                sql+=" and t.create_time <= '" + endTime + "'";
            }
        }
        if (StringUtils.isNoneBlank(orderNo)){
            sql+=" and t.order_no like '%"+orderNo+"%'";
        }
        if (StringUtils.isNoneBlank(yktOrderNo)){
            sql+=" and t.yk_order_no like '%"+yktOrderNo+"%'";
        }
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name  like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(idCard)){
            sql+=" and b.idcard like '%"+idCard+"%'";
        }
        if (StringUtils.isNoneBlank(medicard)){
            sql+=" and t.relation_code like '%"+medicard+"%'";
        }
        if (status!=null){
            sql+=" and t.status ="+status+"";
        }

        if (StringUtils.isNoneBlank(orderType)){
            sql+=" and t.order_type ="+orderType+"";
        }

        if (StringUtils.isNoneBlank(orderCategory)){
            if (orderCategory.equalsIgnoreCase("2")){
                sql+=" and t.order_category IN ('2','3') ";
            }
            sql+=" and t.order_category = '"+orderCategory+"'  ";
        }

        sql+=" order by t.create_time desc ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql);
        for (Map<String,Object> map:mapList){
            if (map.get("orderCategory")!=null){
                String orderCategoryFlag = map.get("orderCategory").toString();
                if (!orderCategoryFlag.equalsIgnoreCase("5")){
                    Double price = Double.parseDouble(map.get("payPrice").toString());
                    Double prie = price/100;
                    logger.info("price"+prie);
                    map.put("payPrice",prie);
                }
            }
        }
        return MixEnvelop.getSuccessListWithPage2(BaseHospitalRequestMapping.Prescription.api_success, mapList);
    }



    public  JSONObject validateGeet( String geetestChallenge,String geetestValidate,String geetestSeccode,String isPatient){

        String validateUrl = "http://localhost:8088/validate";
        List<WlyyHospitalSysDictDO> list = hospitalSysDictDao.findByDictName("geetConfig");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
            if ("validateUrl".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                validateUrl=wlyyHospitalSysDictDO.getDictValue();
            }
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("geetest_challenge",geetestChallenge));
        params.add(new BasicNameValuePair("geetest_validate",geetestValidate));
        params.add(new BasicNameValuePair("geetest_seccode",geetestSeccode));
        params.add(new BasicNameValuePair("isPatient",isPatient));
        String res = httpClientUtil.post(validateUrl, params, "UTF-8");
        JSONObject statusObject = JSONObject.parseObject(res);
        System.out.println(statusObject.toJSONString());
        return statusObject;
    }
    /**
     * 眼科就诊卡充值
     * @param mzhm
     * @param jkje
     * @param type
     * @param paymentType
     * @param patientId
     * @param wechatId
     * @param hospitalId
     * @return
     * @throws Exception
     */
    public Map yktMedicalCardTopUp(String mzhm,Double jkje,Integer type,Integer paymentType,String patientId,String wechatId,String hospitalId,String wxPayType,String appletCode,String geetestChallenge
    ,String geetestValidate,String geetestSeccode) throws Exception {

        String isNeedGeet= "0";//1需要 0不需要
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO1= hospitalSysDictDao.findById("isCardNeedGeet");
        if (wlyyHospitalSysDictDO1!=null){
            isNeedGeet=wlyyHospitalSysDictDO1.getDictValue();
        }
        if("1".equalsIgnoreCase(isNeedGeet)){
            JSONObject resResult =validateGeet(geetestChallenge,geetestValidate,geetestSeccode,"2");
            if (resResult==null||!resResult.getString("result").equalsIgnoreCase("success")){
                throw new  Exception("验证失败");
            }
        }
        BasePatientDO patientDO = patientDao.findById(patientId);
        BusinessOrderDO businessOrderDO = new BusinessOrderDO();
        businessOrderDO.setPatient(patientId);
        businessOrderDO.setPatientName(patientDO.getName());
        businessOrderDO.setCreateTime(DateUtil.getNowDate());
        businessOrderDO.setOrderCategory("5");
        businessOrderDO.setDescription("就诊卡充值");
        businessOrderDO.setPayPrice(jkje);
        businessOrderDO.setOrderNo("HLWYY"+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        businessOrderDO.setRelationCode(mzhm);
        businessOrderDO.setRelationName("就诊卡充值");
        businessOrderDO.setStatus(0);
        if (paymentType==1){
            businessOrderDO.setPayType(2);
        }
        if (paymentType==2){
            businessOrderDO.setPayType(1);
        }
        if (type==0){
            businessOrderDO.setOrderType(10);
        }
        if (type==1){
            businessOrderDO.setOrderType(11);
        }
        Map<String,Object> map= new HashMap<>();
        String rs = ykyyService.getNewSerialNumber(mzhm, jkje.intValue(), type, paymentType, patientDO.getUserId(), hospitalId);
        logger.info("眼科获取充值订单接口调用结果:"+rs);

        Map<String,Object> rsMap = JSONObject.parseObject(rs, Map.class);
        if ("10000".equalsIgnoreCase(rsMap.get("code").toString())){
            businessOrderDO.setYkOrderNo(rsMap.get("value").toString());
        }else {
            logger.info("error=眼科接口调用失败");
            return rsMap;
        }

        businessOrderDO = businessOrderDao.save(businessOrderDO);
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        String openid = "";
        if (StringUtils.isNotBlank(appletCode)){
            logger.info("appletCode不为空"+appletCode);
            Map<String,Object> objectMap = checkApplets(appletCode,wxWechatDO.getApplets(),wxWechatDO.getAppletsSecret());
            if (objectMap!=null){
                openid = objectMap.get("openid").toString();
                logger.info("appletCode"+appletCode);
                logger.info("openid"+openid);
            }
        }else {
            logger.info("appletCode为空"+appletCode);
            if (StringUtils.isNoneBlank(patientId)){
                List<BasePatientWechatDo> patientWechatDo = patientWechatDao.findByWechatIdAndPatientId(wechatId,patientId);
                if (patientWechatDo!=null&&patientWechatDo.size()!=0){
                    openid = patientWechatDo.get(0).getOpenid();
                }
            }
        }
        List<BasePatientWechatDo> patientWechatDoList = patientWechatDao.findByWechatIdAndPatientId(wechatId, patientId);

        if (patientWechatDoList==null || patientWechatDoList.size()==0){
            map.put("error","无openId");
            logger.info("error=无openId");
            return map;
        }
        String url = wxWechatDO.getBaseUrl();
        String notifyUrl =url;
        String price = (int)(businessOrderDO.getPayPrice()*100)+"";
        map = unifiedorder(wechatId,businessOrderDO.getDescription(),price,wxPayType,openid,businessOrderDO.getOrderNo(),notifyUrl,patientId);
        map.put("id",businessOrderDO.getId());
        logger.info("success="+JSONObject.toJSONString(map));
        return map;
    }


}
