package com.yihu.jw.wechat.service;

import com.alibaba.fastjson.JSON;
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.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.entity.base.yx.YxTokenMappingDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.oauth.OauthSsoService;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.order.dao.ConsultOrderDao;
import com.yihu.jw.order.dao.ConsultTeamOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.utils.CheckSumBuilder;
import com.yihu.jw.utils.RSAEncrypt;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.*;
import com.yihu.jw.yx.dao.YxTokenMappingDao;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.*;

/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxTemplateService {

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

    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxTemplateDao wxTemplateDao;

    @Autowired
    private WxAccessTokenService wxAccessTokenService;

    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;

    @Value("${wechat.id}")
    private String wechatId;
    
    @Autowired
    private BasePatientDao basePatientDao;
    
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    
    @Autowired
    private OauthSsoService oauthSsoService;
    
    @Autowired
    private XzzxEntranceService xzzxEntranceService;

    @Autowired
    private YkyyEntranceService ykyyEntranceService;

    @Autowired
    private WxPushLogDao wxPushLogDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private ConsultOrderDao consultOrderDao;
    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Autowired
    private ConsultTeamOrderDao consultTeamOrderDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private YxTokenMappingDao yxTokenMappingDao;
    @Autowired
    private PrescriptionService prescriptionService;


    
    
    /**
     * 发送微信模版消息-小程序视频
     * @param sender_id 发送者ID
     * @param sender_name 发送者姓名
     * @param reciver_id 接收者ID
     * @param reciver_name 接收者姓名
     * @param session_id 会话ID
     */
    public String sendWeTempMesMiniProgram(String sender_id, String sender_name, String reciver_id, String reciver_name,String session_id)throws Exception {
        BasePatientDO basePatientDO = basePatientDao.findById(reciver_id);
        if(basePatientDO!=null){
            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,reciver_id);
            if(ps.isEmpty()){
                logger.info("该用户"+reciver_name+"没有openid,无法推送模版消息，用户ID："+reciver_id+"wechatId:"+wechatId);
            }else{
                for (BasePatientWechatDo basePatientWechatDo:ps){
                    if("xm_xzzx_wx".equals(wechatId)){
                        String getAuthCode = oauthSsoService.getSsoPublic(wechatId,basePatientDO.getId());
    
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("name",basePatientDO.getName());
                        jsonObject.put("idcard",basePatientDO.getIdcard());
                        jsonObject.put("mobile",basePatientDO.getMobile());
                        jsonObject.put("openid",basePatientWechatDo.getOpenid());
                        String authCode = jsonObject.toJSONString();
                        String jm = URLEncoder.encode(RSAEncrypt.encrypt(authCode,getAuthCode),"utf-8");
                        String miniprogramUrl = "pages/room/room?patientCode="+reciver_id+"&doctorName="+sender_name+"&role=patient&roomID="+session_id+"&template=1v1&debugMode=false&cloudenv=PRO&authCode="+jm+"&code="+wechatId+"&appId="+basePatientDO.getId();
                        //心脏中心模版消息推送接口
                        logger.info("心脏中心小程序跳转URL："+miniprogramUrl);
                        xzzxEntranceService.sendXCXMes(wechatId,
                                basePatientDO.getId(),
                                basePatientDO.getIdcard(),
                                sender_name+"主任医生已向您发起视频通话邀请，请点击详情进入视频诊室。",
                                "点击消息进入视频诊室接听视频通话，开始视频咨询",
                                "",miniprogramUrl,"wx53f6bb4ac081d840");
                    }else{

                        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_consult_notice","spthtx",1);
                        BaseDoctorDO doctorDO = doctorDao.findById(sender_id);
                        String titleName = "";
                        if (doctorDO!=null){
                            titleName = doctorDO.getJobTitleName();
                        }
                        String miniprogramUrl = "";
                        config.setFirst(config.getFirst().replace("key1",sender_name+titleName));
                        if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                            String token = yxToken2(reciver_id,reciver_name);
                            miniprogramUrl = "pages/room/yunxin?role=patient&token="+token+"&uid="+basePatientDO.getId();
                            config.setPagepath(miniprogramUrl);
                        }
                        ConsultTeamDo consultDo = consultTeamOrderDao.findByConsult(session_id);
                        WlyyOutpatientDO wlyyOutpatientDO = new WlyyOutpatientDO();
                        if (consultDo!=null){
                            wlyyOutpatientDO = outpatientDao.findById(consultDo.getRelationCode());
                        }
                        if (wlyyOutpatientDO!=null){
                            config.setKeyword2(DateUtil.dateToStrLong(wlyyOutpatientDO.getCreateTime()));
                            config.setKeyword3(wlyyOutpatientDO.getDeptName());
                            config.setKeyword4(wlyyOutpatientDO.getDescription());
                            miniprogramUrl+="&outpatientId="+wlyyOutpatientDO.getId();
                            config.setPagepath(miniprogramUrl);
                        }
                        WxWechatDO wechatDO = wechatDao.findById(wechatId);
                        if (wechatDO!=null){
                            config.setAppid(wechatDO.getApplets());
                        }
                        config.setKeyword1(doctorDO.getName());
                        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),basePatientWechatDo.getOpenid(),config);
                        prescriptionService.wxTempalteJPush("video_invite",wlyyOutpatientDO,null,"","","","");
                    }
                }
            }


        }else{
            throw new Exception("接收者ID错误，无法找到该账号");
        }

        return "success";
    }

  /*  public String yxToken(String userId,String channelName){
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/getToken.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("uid", userId));
        nvps.add(new BasicNameValuePair("channelName",channelName));
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("返回日志"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                return jsonObject.getString("token");
            }
        }
        return null;
    }*/

    public String yxToken2(String userId,String channelName){
        YxTokenMappingDO yxTokenMappingDO = yxTokenMappingDao.findMappingByAccid(userId);
        if (yxTokenMappingDO!=null){
            return yxTokenMappingDO.getToken();
        }
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/create.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", userId));
        YxTokenMappingDO yxTokenMappingDO1 = new YxTokenMappingDO();
        if (StringUtils.isNoneBlank(channelName)){
            nvps.add(new BasicNameValuePair("name",channelName));
            yxTokenMappingDO1.setName(channelName);
        }
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("返回日志"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("info"));
                if (StringUtils.isNoneBlank(jsonObject1.getString("token"))){
                    yxTokenMappingDO1.setAccid(userId);
                    yxTokenMappingDO1.setToken(jsonObject1.getString("token"));
                    yxTokenMappingDao.save(yxTokenMappingDO1);
                }
                return jsonObject1.getString("token");
            }else if (jsonObject.getString("code").equalsIgnoreCase("414")&&jsonObject.getString("desc").contains("already")){
                return  refreshToken(userId);
            }
        }
        return null;
    }

    /**
     * 重置云信token
     * @param userId
     * @return
     */
    public String refreshToken(String userId){
        YxTokenMappingDO yxTokenMappingDO = yxTokenMappingDao.findMappingByAccid(userId);
        if (yxTokenMappingDO!=null){
            return yxTokenMappingDO.getToken();
        }
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("YXAPPKEY");
        WlyyHospitalSysDictDO hospitalSysDictDO =  hospitalSysDictDao.findById("YXAPPSECRET");
        if (sysDictDO==null){
            return  "找不到对应的key";
        }
        String appKey = sysDictDO.getDictValue();
        String appSecret = hospitalSysDictDO.getDictValue();
        String nonce =  randomInt(10);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        String url = "https://api.netease.im/nimserver/user/refreshToken.action";
        Map<String,Object> httpPost = new HashedMap();
        // 设置请求的header
        httpPost.put("AppKey", appKey);
        httpPost.put("Nonce", nonce);
        httpPost.put("CurTime", curTime);
        httpPost.put("CheckSum", checkSum);
        httpPost.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", userId));
        YxTokenMappingDO yxTokenMappingDO1 = new YxTokenMappingDO();
        String response = httpClientUtil.headerPost(url,nvps,"UTF-8",httpPost);
        logger.info("重置云信"+response);
        if(StringUtils.isNoneBlank(response)){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
            if (jsonObject.getString("code").equalsIgnoreCase("200")){
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.getString("info"));
                if (StringUtils.isNoneBlank(jsonObject1.getString("token"))){
                    yxTokenMappingDO1.setAccid(userId);
                    yxTokenMappingDO1.setToken(jsonObject1.getString("token"));
                    yxTokenMappingDao.save(yxTokenMappingDO1);
                }
                return jsonObject1.getString("token");
            }
        }
        return null;
    }

    /**
     * 获取指定长度的随机数字字符串
     * @param length
     * @return
     */
    public String randomInt(int length) {
        String str = "0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for(int i = 0; i < length; ++i) {
            int pos = random.nextInt(str.length());
            buffer.append(str.charAt(pos));
        }
        return buffer.toString();
    }

    /**
     * 查询HIS的01表中的审方状态，如果已审方，且未结算，则推送一条模板消息给居民，让居民进行支付结算。
     */
    public void unSettledHISPrescription() throws Exception{
        if("xm_ykyy_wx".equals(wechatId)){
            //获取审核失败
            JSONArray jsonArray = ykyyEntranceService.getNoUnsettledPrescription();
            if(jsonArray!=null&&jsonArray.size()>0) {
                for (int i = 0; i<jsonArray.size(); i++){
                    JSONObject json = jsonArray.getJSONObject(i);
                    String cfsb = json.getString("CFSB");
                    //查找对应的处方
                    String sql = "SELECT w.OUTPATIENT_ID,w.ID,w.DOCTOR_NAME from WLYY_PRESCRIPTION w WHERE REAL_ORDER = '"+cfsb+"' ORDER BY w.CREATE_TIME desc";
                    List<Map<String, Object>> pre = hibenateUtils.createSQLQuery(sql);
                    if(pre!=null && pre.size()>0){
                        String prescriptionId = pre.get(0).get("ID").toString();
                        //修改处方状态
                        String updateSql = "update WLYY_PRESCRIPTION set status = 11 where id = '"+prescriptionId+"'";
                        hibenateUtils.updateBySql(updateSql);
                    }
                }
            }
            //获取已审核未结算的处方
            JSONArray array = ykyyEntranceService.getUnsettledPrescription();
            //发送模板
            if(array!=null&&array.size()>0) {
                for (int i = 0; i<array.size(); i++){
                    JSONObject json = array.getJSONObject(i);
                    String brid = json.getString("BRID");
                    String cfsb = json.getString("CFSB");

                    //查找居民信息
                    BasePatientDO patientDO = ykyyEntranceService.findPatientByMapingCode(brid);
                    if(patientDO!=null){
                        //查找对应的处方
                        String sql = "SELECT w.OUTPATIENT_ID,w.ID,w.DOCTOR_NAME from WLYY_PRESCRIPTION w WHERE REAL_ORDER = '"+cfsb+"' ORDER BY w.CREATE_TIME desc";
                        List<Map<String, Object>> pre = hibenateUtils.createSQLQuery(sql);
                        if(pre!=null && pre.size()>0){
                            String outpatientId = pre.get(0).get("OUTPATIENT_ID").toString();
                            String prescriptionId = pre.get(0).get("ID").toString();
                            String doctorName = pre.get(0).get("DOCTOR_NAME").toString();



                            //判断是否发送过
                            String countSql = "SELECT id from WX_PUSH_LOG w WHERE w.RECEIVER = '"+patientDO.getId()
                                    +"' and w.OPENID = '"+prescriptionId+"' and w.scene = 'djsxxtz' and w.WECHAT_ID='"+wechatId+"'";
                            List<Map<String, Object>> count = hibenateUtils.createSQLQuery(countSql);
                            if(count==null || count.size() == 0){
                                List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,patientDO.getId());
                                if(ps.isEmpty()){
                                    logger.info("该用户"+patientDO.getName()+"没有openid,无法推送模版消息，用户ID："+patientDO.getId()+"wechatId:"+wechatId);
                                }else{
                                    //修改处方状态
                                    String updateSql = "update WLYY_PRESCRIPTION set status = 20 where id = '"+prescriptionId+"' and status = 10";
                                    hibenateUtils.updateBySql(updateSql);
                                    prescriptionLogService.addPrescriptionLog(prescriptionId,20,2,"system","system","",new Date());

                                    ps.stream().forEach(one->{
                                        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_unsettled_notice","djsxxtz",1);
                                        WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
                                        BeanUtils.copyProperties(config,newConfig);
                                        newConfig.setFirst(config.getFirst().replace("key1",patientDO.getName()));
                                        if (StringUtils.isNoneBlank(config.getPagepath())){
                                            String path = "returnVisit/record?outpatientId="+outpatientId;
                                            newConfig.setPagepath(config.getPagepath()+URLEncoder.encode(path));
                                        }
                                        newConfig.setUrl(config.getUrl()+""+outpatientId);
                                        newConfig.setKeyword3(doctorName);
                                        WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
                                        logger.info("=======setUrl========"+newConfig.getUrl());
                                        weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(),one.getOpenid(),newConfig);
                                    });
                                    //保存发送模板记录,
                                    WxPushLogDO wxPushLogDO = new WxPushLogDO();
                                    wxPushLogDO.setCreateTime(new Date());
                                    wxPushLogDO.setOpenid(prescriptionId);
                                    wxPushLogDO.setReceiver(patientDO.getId());
                                    wxPushLogDO.setWechatId(wechatId);
                                    wxPushLogDO.setReceiverName(patientDO.getName());
                                    wxPushLogDO.setScene("djsxxtz");
                                    wxPushLogDao.save(wxPushLogDO);
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    public void updateStatusByPayTime() throws Exception{
        if("xm_ykyy_wx".equals(wechatId)){
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("PAY_TIME");
            if (wlyyHospitalSysDictDO!=null){
                String remind = wlyyHospitalSysDictDO.getDictValue();
                String close = wlyyHospitalSysDictDO.getDictCode();
                List<BusinessOrderDO> businessOrderDOS = businessOrderDao.selectByStatus(0);
                //关闭处理
                for (BusinessOrderDO businessOrderDO:businessOrderDOS){
                    Calendar cal= Calendar.getInstance();
                    cal.setTime(businessOrderDO.getCreateTime());
                    cal.add(Calendar.MINUTE,Integer.parseInt(close));
                    Long now = new Date().getTime();
                    Long min = cal.getTime().getTime();
                    logger.info("关闭处理cal="+cal);
                    if (min==now){
                        String orderCategory = businessOrderDO.getOrderCategory();
                        String relationCode = businessOrderDO.getRelationCode();
                        if (orderCategory.equalsIgnoreCase("1")){
                            ConsultTeamDo consultTeamDo = consultTeamOrderDao.findByConsult(relationCode);
                            consultTeamDo.setStatus(-1);
                            consultTeamOrderDao.save(consultTeamDo);
                        }else if (orderCategory.equalsIgnoreCase("2")){
                            WlyyOutpatientDO outpatientDO = outpatientDao.findById(relationCode);
                            outpatientDO.setStatus("-1");
                            outpatientDao.save(outpatientDO);
                        }
                    }

                }
                //提醒处理
                for (BusinessOrderDO businessOrderDO:businessOrderDOS){
                    String orderCategory = businessOrderDO.getOrderCategory();
                    String relationCode = businessOrderDO.getRelationCode();
                    String orderType =businessOrderDO.getOrderType()+"";
                    String doctor = businessOrderDO.getDoctor();
                    String patient= businessOrderDO.getPatient();

                    Calendar cal= Calendar.getInstance();
                    cal.setTime(businessOrderDO.getCreateTime());
                    cal.add(Calendar.MINUTE,Integer.parseInt(remind));
                    Long now = new Date().getTime();
                    Long min = cal.getTime().getTime();
                    logger.info("提醒处理cal="+cal);
                    if (min==now){
                        //判断是否发送过
                        String countSql = "SELECT id from WX_PUSH_LOG w WHERE w.RECEIVER = '"+patient
                                +"' and w.OPENID = '"+relationCode+"' and w.scene = 'zxzfts' and w.WECHAT_ID='"+wechatId+"'";
                        List<Map<String, Object>> count = hibenateUtils.createSQLQuery(countSql);
                        if(count==null || count.size() == 0){
                            BasePatientDO patientDO = basePatientDao.findById(patient);
                            BaseDoctorDO doctorDO = doctorDao.findById(doctor);
                            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,patient);
                            if(ps.isEmpty()){
                                logger.info("该用户"+patientDO.getName()+"没有openid,无法推送模版消息，用户ID："+patientDO.getId()+"wechatId:"+wechatId);
                            }else{

                                ps.stream().forEach(one->{
                                    WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_unsettled_notice","zxzfts",1);
                                    WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
                                    BeanUtils.copyProperties(config,newConfig);
                                    String name = "";
                                    String condition="";
                                    if (orderCategory.equalsIgnoreCase("1")){
                                        if (orderType.equalsIgnoreCase("1")){
                                            name="图文咨询";
                                        }else if (orderType.equalsIgnoreCase("3")){
                                            name="视频咨询";
                                        }
                                        condition = "&consultCode="+relationCode;
                                    }else if (orderCategory.equalsIgnoreCase("2")){
                                        if (orderType.equalsIgnoreCase("1")){
                                            name="图文咨询";
                                        }else if (orderType.equalsIgnoreCase("3")){
                                            name="视频咨询";
                                        }
                                        condition = "&outpatientId="+relationCode;
                                    }
                                    newConfig.setFirst(config.getFirst().replace("key1",patientDO.getName()).replace("key2",name));
                                    if (StringUtils.isNoneBlank(config.getPagepath())){
                                        String path = "returnVisit/record?outpatientId="+relationCode;
                                        newConfig.setPagepath(config.getPagepath()+URLEncoder.encode(path));
                                    }
                                    newConfig.setUrl(config.getUrl()+""+condition);
                                    newConfig.setKeyword3(doctorDO.getName());
                                    newConfig.setKeyword1(name);
                                    WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
                                    logger.info("=======setUrl========"+newConfig.getUrl());
                                    weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(),one.getOpenid(),newConfig);
                                });
                                //保存发送模板记录,
                                WxPushLogDO wxPushLogDO = new WxPushLogDO();
                                wxPushLogDO.setCreateTime(new Date());
                                wxPushLogDO.setOpenid(relationCode);
                                wxPushLogDO.setReceiver(patientDO.getId());
                                wxPushLogDO.setWechatId(wechatId);
                                wxPushLogDO.setReceiverName(patientDO.getName());
                                wxPushLogDO.setScene("zxzfts");
                                wxPushLogDao.save(wxPushLogDO);
                            }
                        }
                    }
                }
            }
        }
    }
    
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_survey","test",1);
        config.setFirst(config.getFirst().replace("key1","小明"));
        config.setKeyword2("2018-08-21");
        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),openid,config);
        return "success";
    }
    

    public Envelop getAllTemp(String wechatId){

        String url ="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken();
        String result = HttpUtil.sendGet(url);

        JSONObject tempJsons = JSON.parseObject(result);
        //获取所有本地模板
        List<String> localTemps = findAllTempDos(wechatId);
        //解析公众号模板
        JSONArray temps = tempJsons.getJSONArray("template_list");

        List<WxTemplateDO> savelist = new ArrayList<>();

        if(temps!=null&&!temps.isEmpty()){
            for(int i=0;i<temps.size();i++){
                JSONObject tp = (JSONObject) temps.get(i);
                String tpid = tp.getString("template_id");
                if(!localTemps.contains(tpid)){
                    WxTemplateDO wxTemplateDO = new WxTemplateDO();
                    wxTemplateDO.setWechatId(wechatId);
                    wxTemplateDO.setTemplateId(tpid);
                    wxTemplateDO.setTitle(tp.getString("title"));
                    wxTemplateDO.setContent(tp.getString("content"));
                    wxTemplateDO.setStatus(1);
                    wxTemplateDO.setCreateTime(new Date());
                    savelist.add(wxTemplateDO);
                }
            }

            wxTemplateDao.save(savelist);
        }
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);

    }

    public List<String> findAllTempDos(String wechatId){
        List<WxTemplateDO> list =  wxTemplateDao.findByWxId(wechatId);
        List<String> rs = new ArrayList<>();
        if(list!=null&&list.size()>0){
            for(WxTemplateDO wxTemplateDO:list){
                rs.add(wxTemplateDO.getTemplateId());
            }
        }
        return rs;
    }
    
    /**
     * 发送微信模版消息
     * @param userName
     * @param senderName
     * @param idCard
     * @param phone
     * @param title
     * @param content
     * @param contentString
     * @param url
     */
    public String sendWxTemple(String userName, String senderName,
                             String idCard, String phone, String title,
                             String content, String contentString,
                             String url) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findByIdcard(idCard);
        if(basePatientDO!=null){
            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,basePatientDO.getId());
            if(ps.isEmpty()){
                logger.info("该用户"+basePatientDO.getName()+"没有openid,无法推送模版消息，用户ID："+basePatientDO.getId()+"wechatId:"+wechatId);
            }else{
                for (BasePatientWechatDo basePatientWechatDo:ps){
                        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_im_notice","zxtx",1);
                        config.setFirst(config.getFirst().replace("key1",userName));
                        config.setKeyword1(contentString);
                        config.setKeyword2(DateUtil.dateToStrLong(new Date()));
                        if (StringUtils.isNoneBlank(config.getPagepath())){
                            String path = URLEncoder.encode(url.replace("https://intel.yanketong.com/ims-wx/index.html#/",""));
                            config.setPagepath(config.getPagepath()+path);
                        }
                        config.setUrl(url);
                        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),basePatientWechatDo.getOpenid(),config);
                }

            }
            List<WlyyOutpatientDO> list = outpatientDao.findWlyyOutpatientDO(basePatientDO.getId());
            if (list!=null&&list.size()>0){
                WlyyOutpatientDO wlyyOutpatientDO = list.get(0);
                wlyyOutpatientDO.setConsumer(basePatientDO.getId());
                wlyyOutpatientDO.setDoctorName(senderName);
                prescriptionService.wxTempalteJPush("consult_remind",wlyyOutpatientDO,null,"","","","");
            }

        }else{
            throw new Exception("接收者ID错误，无法找到该账号");
        }
        return "success";
    }


    /**
     * 发送微信模版消息
     * @param userName
     * @param senderName
     * @param idCard
     * @param phone
     * @param title
     * @param content
     * @param contentString
     * @param url
     */
    public String sendAppletWxTemple(String userName, String senderName,
                               String idCard, String phone, String title,
                               String content, String contentString,
                               String url,String pagePath) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findByIdcard(idCard);
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if(basePatientDO!=null){
            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,basePatientDO.getId());
            if(ps.isEmpty()){
                logger.info("该用户"+basePatientDO.getName()+"没有openid,无法推送模版消息，用户ID："+basePatientDO.getId()+"wechatId:"+wechatId);
            }else{
                for (BasePatientWechatDo basePatientWechatDo:ps){
                    WxTemplateConfigDO config = new WxTemplateConfigDO();
                    config.setFirst(config.getFirst().replace("key1",userName));
                    config.setKeyword1(contentString);
                    config.setKeyword2(DateUtil.dateToStrLong(new Date()));
                    config.setUrl(url);
                    config.setAppid(wxWechatDO.getApplets());
                    config.setPagepath(pagePath);
                    weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),basePatientWechatDo.getOpenid(),config);
                }
            }
        }else{
            throw new Exception("接收者ID错误，无法找到该账号");
        }
        return "success";
    }
}
