@Action("pushresult")
  public String pushresult() throws IOException {
    DB db = MongoUtil.getInstance().getDB();
    BasicDBObject ret = null;
    if (checkTime(timestamp)) {
      if (checkenc(db, timestamp, clientid, userenc)) {
        DBObject dbo = db.getCollection("Pushmsgs").findOne(new BasicDBObject("msgid", msgid));
        if (!CommonUtil.isEmpty(dbo)) {
          ret =
              new BasicDBObject()
                  .append("msgid", dbo.get("msgid"))
                  .append("status", dbo.get("status"));
        } else {
          errormsg = "Message not found";
        }
      } else {
        errormsg = "User not authorized";
      }
    } else errormsg = "Timestamp outof range";

    HttpServletResponse resp = ServletActionContext.getResponse();
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("application/json");
    if (!CommonUtil.isEmpty(ret)) resp.getWriter().print(JSON.serialize(ret));
    else resp.getWriter().write("{\"errcode\":50000,\"errmsg\":\"" + errormsg + "\"}");

    return NONE;
  }
  /**
   * 通过PWD跳转到支付页面
   *
   * @return
   * @throws IOException
   */
  @Action("ecardpwd")
  public String pwd() throws IOException {
    Object openid = getSession().get("openid");
    HttpServletResponse resp = org.apache.struts2.ServletActionContext.getResponse();
    Map<String, Object> ret = new HashMap<String, Object>();
    if (!CommonUtil.isEmpty(openid)) {
      DBObject payinfo = SWEcardModel.getPwd(uisid);
      DBObject user =
          MongoUtil.getInstance()
              .getDB()
              .getCollection("Bindings")
              .findOne(new BasicDBObject("openid", openid));
      binds = new TACOAuth2Model().fetchUserinfo(user);
      if (binds != null && binds.size() > 0) {
        boolean found = false;
        for (Object b : binds) {
          if (b instanceof Map) {
            Map bm = (Map) b;
            String uid = String.valueOf(bm.get("user_id"));
            if (CommonUtil.eq(uid, payinfo.get("uisid"))) {
              found = true;
            }
          }
        }
        if (!found) {
          addActionError("订单的UISID不匹配");
        } else {
          ret.put("retcode", 0);
          ret.put(
              "url",
              WiscomPayModel.formupDirecturl(
                  String.valueOf(openid),
                  String.valueOf(payinfo.get("uisid")),
                  String.valueOf(payinfo.get("pwd"))));
        }

      } else {
        addActionError(" 尚未对任何账号授权");
      }

    } else {
      addActionError("尚未登录");
    }
    if (hasErrors()) {

      ret.put("retcode", -500);
      ret.put("retmsg", getActionErrors());
    }
    resp.setCharacterEncoding("utf-8");
    JSON.writeJSONStringTo(ret, resp.getWriter());

    return NONE;
  }
  public void clearDangerMultiBind() {

    DBCollection dc = MongoUtil.getInstance().getCollection("Bindings");
    DBCursor c = dc.find();
    JSONMessageBuilder bd = new JSONMessageBuilder();
    bd.setContent(
        "由于我们发现您绑定了多个不同姓名的账号,为保护个人隐私我们已经将您所有的绑定信息清空,如需继续使用请重新绑定自己的UIS账号。我们不推荐帮助其他人查询个人信息。");

    while (c.hasNext()) {
      DBObject obj = c.next();
      try {
        BasicDBList binds = (BasicDBList) obj.get("binds");
        if (binds.size() > 1) {
          Object name = null;
          for (int i = 0; i < binds.size(); i++) {
            DBObject u = (DBObject) binds.get(i);
            if (i > 0) {
              if (u.get("username") == null || !u.get("username").equals(name)) {
                dc.remove(obj);

                System.out.println(obj);
                bd.set("touser", obj.get("openid"));
                System.out.println(
                    CommonUtil.postWebRequest(
                        "https://api.weixin.qq.com/cgi-bin/message/custom/"
                            + "send?access_token="
                            + AccessTokenHelper.getInstance().getToken(AccessTokenHelper.WEIXIN),
                        WeixinMessageHelper.msg2jsonstr(bd.getMessage()).getBytes("utf-8"),
                        "application/json; charset=utf-8"));
              }
              break;
            }
            name = u.get("username");
          }
        }
      } catch (Exception ex) {

      }
    }
  }
 /**
  * 一卡通充值入口界面预处理
  *
  * @return
  * @throws IOException
  */
 @Action("ecardpre")
 public String prepaid() throws IOException {
   Object openid = getSession().get("openid");
   if (!CommonUtil.isEmpty(openid)) {
     DBObject user =
         MongoUtil.getInstance()
             .getDB()
             .getCollection("Bindings")
             .findOne(new BasicDBObject("openid", openid));
     binds = new TACOAuth2Model().fetchUserinfo(user);
     if (binds != null && binds.size() > 0) {
       for (Object b : binds) {
         if (b instanceof Map) {
           Map bm = (Map) b;
           String uid = String.valueOf(bm.get("user_id"));
           bm.put("unpaid", SWEcardModel.unpaid(uid));
         }
       }
     }
   }
   if (binds == null) binds = new ArrayList();
   return SUCCESS;
 }
  @Test
  public void findMultiUis() {
    DBCollection dc = MongoUtil.getInstance().getCollection("Bindings");
    DBCollection dc2 = MongoUtil.getInstance().getCollection("weixinuser");
    DBCursor c = dc.find();
    Map<String, Integer> holder = new HashMap<String, Integer>();
    while (c.hasNext()) {
      try {
        DBObject obj = c.next();
        BasicDBList binds = (BasicDBList) obj.get("binds");
        if (binds != null)
          for (Object o : binds) {
            DBObject user = (DBObject) o;
            String id = user.get("uisid").toString();
            Integer i = holder.get(id);
            if (i == null) i = 1;
            else i++;
            holder.put(id, i);
          }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }

    for (Entry<String, Integer> entry : holder.entrySet()) {
      if (entry.getValue() > 1) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
        DBCursor c2 =
            dc.find(
                new BasicDBObject(
                    "binds",
                    new BasicDBObject("$elemMatch", new BasicDBObject("uisid", entry.getKey()))));

        String nickname = "";
        while (c2.hasNext()) {
          try {
            DBObject binding = c2.next();
            DBObject wxusr = dc2.findOne(new BasicDBObject("openid", binding.get("openid")));
            nickname += "\"" + wxusr.get("nickname") + "\", ";

          } catch (Exception e) {

          }
        }
        System.out.println(nickname);
        if (entry.getKey().matches("\\d{7,}")) {
          SMTP smtp = new ServiceMail();
          smtp.addTo(entry.getKey() + "@fudan.edu.cn");
          smtp.setTitle("信息办微信公众号绑定风险提示");
          try {
            smtp.setMailbody(
                "同学你好,\n我们发现你的学号绑定到了"
                    + entry.getValue()
                    + "个不同的微信号,昵称分别为:"
                    + nickname
                    + "如果其中有不是你希望绑定到的微信号请尽快与信息办联系,电话65643207,邮件:[email protected]",
                false);
            smtp.send();
            System.out.println("邮件发送:" + entry.getKey());
          } catch (MessagingException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  @Action("wxlogindo")
  public String logindo() {
    // Cache cache= CacheManager.getInstance().getCache("WXStates");
    // Element el=cache.get(state);
    if (!CommonUtil.isEmpty(code)
        && !CommonUtil.isEmpty(state)
        && state.equals(getSession().remove("wxstate"))) {

      redir = String.valueOf(getSession().remove("redir"));
      // cache.removeElement(el);
      Config conf = Config.getInstance();
      // 获取微信的access_token
      String urlstr =
          "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
              + conf.get("weixin.appid")
              + "&secret="
              + conf.get("weixin.secret")
              + "&code="
              + code
              + "&grant_type=authorization_code";
      try {
        String ret = CommonUtil.getWebContent(urlstr).toString();
        DBObject retobj = (DBObject) JSON.parse(ret);
        Object acctk = retobj.get("access_token");
        if (!CommonUtil.isEmpty(acctk)) {
          // 更新Bindings库中的access_token
          DBCollection c = MongoUtil.getInstance().getDB().getCollection("Bindings");
          Object openid = retobj.get("openid");
          // 设置Session
          getSession().put("openid", openid);
          DBObject obj = c.findOne(new BasicDBObject("openid", openid));
          if (CommonUtil.isEmpty(obj)) {
            obj = new BasicDBObject().append("openid", retobj.get("openid"));
          }
          obj.put("weixintoken", acctk);
          obj.put(
              "weixinexpired", System.currentTimeMillis() + 1000 * (int) retobj.get("expires_in"));
          obj.put("weixinscope", retobj.get("scope"));
          obj.put("wexinrefresh", retobj.get("refresh_token"));
          c.save(obj);
          /*
           * if(obj.get("binds")!=null &&obj.get("binds") instanceof
           * List) { List<BasicDBObject> ls=new
           * ArrayList<BasicDBObject>(); for(DBObject
           * ob:(List<DBObject>)obj.get("binds")) {
           * if(!CommonUtil.isEmpty(ob)){ BasicDBObject bdo=new
           * BasicDBObject(); bdo.put("uisid", ob.get("uisid"));
           * bdo.put("username",ob.get("username"));
           * bdo.put("usertype", ob.get("usertype")); ls.add(bdo); } }
           * getSession().put("binds", ls); }
           */

          DBObject user =
              MongoUtil.getInstance()
                  .getDB()
                  .getCollection("weixinuser")
                  .findOne(new BasicDBObject("openid", openid));
          if (!CommonUtil.isEmpty(user)) getSession().put("nickname", user.get("nickname"));

        } else {
          log.error(ret);
        }
      } catch (Exception e) {
        log.error(e);
      }
      try {
        org.apache.struts2.ServletActionContext.getResponse().sendRedirect(redir);
      } catch (Exception e) {
        log.error(e);
      }
    } else {
      try {
        org.apache.struts2.ServletActionContext.getResponse()
            .getWriter()
            .write("Unreconginzed reqest!");
      } catch (IOException e) {
        log.error(e);
      }
    }
    return NONE;
  }
  @Action("msgpush")
  public String msgpush() throws Exception {
    BufferedReader r = ServletActionContext.getRequest().getReader();
    String ret = null;
    StringBuffer sb = new StringBuffer();
    String s;
    while ((s = r.readLine()) != null) {
      sb.append(s);
    }
    DBObject req = (DBObject) JSON.parse(sb.toString());
    DBObject head = (DBObject) req.get("head");
    timestamp = (long) head.get("timestamp");
    clientid = String.valueOf(head.get("clientid"));
    userenc = String.valueOf(head.get("userenc"));
    String touser = String.valueOf(head.get("touser"));
    DB db = MongoUtil.getInstance().getDB();
    if (checkTime(timestamp)) {
      if (checkenc(db, timestamp, clientid, userenc)) {
        if (checkmsgsum(req.get("data"), touser, userenc, String.valueOf(head.get("checksum")))) {
          Cache cache = CacheManager.getInstance().getCache("MsgCheck");
          if (cache.get(head.get("checksum")) == null) {
            cache.put(new Element(head.get("checksum"), null));
            DBObject user =
                db.getCollection("Bindings")
                    .findOne(
                        new BasicDBObject(
                            "binds",
                            new BasicDBObject("$elemMatch", new BasicDBObject("uisid", touser))));
            if (!CommonUtil.isEmpty(user) && !CommonUtil.isEmpty(user.get("openid"))) {
              // template白名单
              if (Config.getInstance()
                          .get("push.whitelist")
                          .indexOf(head.get("template").toString())
                      >= 0
                  || db.getCollection("Books")
                          .findOne(
                              new BasicDBObject("openid", user.get("openid"))
                                  .append("item", head.get("template"))
                                  .append("book", true))
                      != null) {
                String cret =
                    TemplateMessage.send(
                        String.valueOf(head.get("template")),
                        String.valueOf(user.get("openid")),
                        (DBObject) req.get("data"));
                if (cret != null && cret.startsWith("{")) {
                  DBObject retobj = (DBObject) JSON.parse(cret);
                  retobj.put("touser", touser);
                  retobj.put("timestamp", timestamp);
                  retobj.put("clientid", clientid);
                  db.getCollection("Pushmsgs").save(retobj);
                  ret = cret;
                } else errormsg = cret;
              } else {
                errormsg = "Message not booked";
              }
            } else {
              errormsg = "Touser not binded";
            }

          } else {
            errormsg = "Same message is sent too frequently";
          }
        } else {
          errormsg = "Message checksum error";
        }

      } else {
        errormsg = "User not authorized";
      }
    } else errormsg = "Timestamp outof range";

    HttpServletResponse resp = ServletActionContext.getResponse();
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("application/json");
    if (!CommonUtil.isEmpty(ret)) resp.getWriter().print(ret);
    else resp.getWriter().write("{\"errcode\":50000,\"errmsg\":\"" + errormsg + "\"}");

    return NONE;
  }