public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    JObject jobject = new JObject();
    try {

      String pin = (String) request.getAttribute("pin");
      Staff staff = StaffDao.verify(Integer.parseInt(pin));

      String reason = request.getParameter("reason");
      CancelReason.InsertBuilder builder = new InsertBuilder(staff.getRestaurantId(), reason);
      CancelReasonDao.insert(staff, builder);
      jobject.initTip(true, "操作成功, 已添加退菜原因信息.");
    } catch (BusinessException e) {
      e.printStackTrace();
      jobject.initTip(e);
    } catch (Exception e) {
      e.printStackTrace();
      jobject.initTip4Exception(e);
    } finally {
      response.getWriter().print(jobject.toString());
    }
    return null;
  }
  private Staff compareRoleAndStaff(int restaurantId) throws SQLException, BusinessException {

    Staff expectedStaff = StaffDao.getByRestaurant(restaurantId).get(0);
    Assert.assertEquals("admin staff restaurant id", expectedStaff.getRestaurantId(), restaurantId);
    Assert.assertEquals(
        "admin staff type", expectedStaff.getType().getVal(), Staff.Type.RESERVED.getVal());
    Assert.assertEquals(
        "admin staff role type",
        expectedStaff.getRole().getCategory().getVal(),
        Role.Category.ADMIN.getVal());
    Assert.assertEquals("admin staff name", expectedStaff.getName(), Staff.AdminBuilder.ADMIN);

    compareRole(restaurantId, expectedStaff, Role.Category.ADMIN, Role.Type.RESERVED);

    compareRole(restaurantId, expectedStaff, Role.Category.BOSS, Role.Type.RESERVED);

    compareRole(restaurantId, expectedStaff, Role.Category.FINANCE, Role.Type.NORMAL);

    compareRole(restaurantId, expectedStaff, Role.Category.MANAGER, Role.Type.NORMAL);

    compareRole(restaurantId, expectedStaff, Role.Category.CASHIER, Role.Type.NORMAL);

    compareRole(restaurantId, expectedStaff, Role.Category.WAITER, Role.Type.NORMAL);

    return expectedStaff;
  }
  /**
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  public ActionForward getInfo(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    JObject jobject = new JObject();
    try {
      int restaurantId = WxRestaurantDao.getRestaurantIdByWeixin(request.getParameter("fid"));
      final String info =
          WxRestaurantDao.get(StaffDao.getAdminByRestaurant(restaurantId)).getWeixinInfo();
      jobject.setExtra(
          new Jsonable() {

            @Override
            public JsonMap toJsonMap(int flag) {
              JsonMap jm = new JsonMap();
              jm.putString("info", info);
              return jm;
            }

            @Override
            public void fromJsonMap(JsonMap jsonMap, int flag) {}
          });
      jobject.setSuccess(true);
    } catch (Exception e) {
      e.printStackTrace();
      jobject.initTip4Exception(e);
    } finally {
      response.getWriter().print(jobject.toString());
    }
    return null;
  }
 @BeforeClass
 public static void initDbParam() throws PropertyVetoException, BusinessException {
   TestInit.init();
   try {
     mStaff = StaffDao.getAdminByRestaurant(37);
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
 @BeforeClass
 public static void initDBParam() throws BusinessException, SQLException, PropertyVetoException {
   TestInit.init();
   try {
     mStaff = StaffDao.getByRestaurant(37).get(0);
     mStaff.setRestaurantId(26);
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    JObject jobject = new JObject();
    List<PrintFunc> root;
    try {
      String pin = (String) request.getAttribute("pin");
      String printerId = request.getParameter("printerId");
      Staff staff = StaffDao.verify(Integer.parseInt(pin));
      root =
          PrintFuncDao.getByCond(
              staff, new PrintFuncDao.ExtraCond().setPrinter(Integer.parseInt(printerId)));
      List<PrintFunc> roots = new ArrayList<PrintFunc>();

      boolean detail = true;
      for (PrintFunc printFunc : root) {
        if (printFunc.getType() == PType.PRINT_ORDER_DETAIL
            || printFunc.getType() == PType.PRINT_CANCELLED_FOOD_DETAIL) {
          if (printFunc.getType() == PType.PRINT_ORDER_DETAIL) {
            if (detail) {
              roots.add(printFunc);
              detail = false;
            }
          } else if (printFunc.getType() == PType.PRINT_CANCELLED_FOOD_DETAIL) {
            if (detail) {
              printFunc.setType(PType.PRINT_ORDER_DETAIL);
              roots.add(printFunc);
              detail = false;
            }
          }
        } else {
          roots.add(printFunc);
        }
      }

      jobject.setTotalProperty(roots.size());
      jobject.setRoot(roots);

    } catch (BusinessException e) {
      jobject.initTip(e);
      e.printStackTrace();

    } catch (Exception e) {
      jobject.initTip4Exception(e);
      e.printStackTrace();
    } finally {

      response.getWriter().print(jobject.toString());
    }
    return null;
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    JObject jobject = new JObject();
    SystemSetting set = null;
    try {

      String pin = (String) request.getAttribute("pin");
      StaffDao.verify(Integer.parseInt(pin));

      String restaurantID = (String) request.getAttribute("restaurantID");
      String priceTail = request.getParameter("priceTail");
      String eraseQuota = request.getParameter("eraseQuota");

      if (restaurantID == null || restaurantID.trim().isEmpty()) {
        jobject.initTip(false, "操作失败, 获取餐厅信息失败.");
        return null;
      }

      if (priceTail == null || priceTail.trim().isEmpty()) {
        jobject.initTip(false, "操作失败, 获取收款金额尾数处理方式失败.");
        return null;
      }
      if (eraseQuota == null || eraseQuota.trim().isEmpty()) {
        jobject.initTip(false, "操作失败, 获取抹数金额上限失败.");
        return null;
      }

      set = new SystemSetting();
      set.getSetting().setPriceTail(Integer.parseInt(priceTail));
      set.getSetting().setEraseQuota(Integer.parseInt(eraseQuota));
      set.setRestaurantID(Integer.parseInt(restaurantID));

      SystemDao.updatePriceTail(set);
      jobject.initTip(true, "操作成功, 已修改收款设置.");

    } catch (BusinessException e) {
      e.printStackTrace();
      jobject.initTip(e);

    } catch (Exception e) {
      e.printStackTrace();
      jobject.initTip4Exception(e);
    } finally {
      response.getWriter().print(jobject.toString());
    }

    return null;
  }
 public static Result cleanup() throws SQLException, BusinessException {
   long beginTime = System.currentTimeMillis();
   DBCon dbCon = new DBCon();
   try {
     dbCon.connect();
     int amount = 0;
     // Delete all the invalid and committed wx order.
     for (Restaurant restaurant : RestaurantDao.getByCond(null, null)) {
       amount +=
           deleteByCond(dbCon, StaffDao.getAdminByRestaurant(dbCon, restaurant.getId()), null);
     }
     return new Result(amount, (int) (System.currentTimeMillis() - beginTime) / 1000);
   } finally {
     dbCon.disconnect();
   }
 }
  public static ArchiveResult archive() throws SQLException, BusinessException {
    long beginTime = System.currentTimeMillis();

    ArchiveResult result = new ArchiveResult();
    DBCon dbCon = new DBCon();
    try {
      dbCon.connect();
      // dbCon.conn.setAutoCommit(false);
      for (Restaurant restaurant : RestaurantDao.getByCond(dbCon, null, null)) {
        Staff staff = StaffDao.getAdminByRestaurant(dbCon, restaurant.getId());
        // Archive the expired order.
        OrderDao.ArchiveResult orderResult = OrderDao.archive4Expired(dbCon, staff);
        result.orderAmount += orderResult.orderAmount;
        result.ofAmount += orderResult.ofAmount;
        result.tgAmount += orderResult.tgAmount;
        result.mixedAmount += orderResult.mixedAmount;

        // Archive the expired payment.
        result.paymentAmount += PaymentDao.archive4Expired(dbCon, staff);

        // Archive the expired shift.
        result.shiftAmount += ShiftDao.archive4Expired(dbCon, staff);

        // Archive the expired daily.
        result.dailyAmount += DailySettleDao.archive4Expired(dbCon, staff);

        // Archive the expired member operation.
        result.moAmount += MemberOperationDao.archive4Expired(dbCon, staff).getAmount();
      }
      // dbCon.conn.commit();
    } catch (BusinessException | SQLException e) {
      // dbCon.conn.rollback();
      throw e;
    } finally {
      dbCon.disconnect();
    }

    result.elapsedTime = ((int) (System.currentTimeMillis() - beginTime) / 1000);
    return result;
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    try {
      Restaurant restaurant = RestaurantDao.getById(Integer.parseInt(request.getParameter("rid")));

      AuthorizationInfo authorizationInfo =
          AuthorizationInfo.newInstance(
              AuthParam.COMPONENT_ACCESS_TOKEN, request.getParameter("auth_code"));
      // System.out.println(authorizationInfo);

      AuthorizerInfo authorizerInfo =
          AuthorizerInfo.newInstance(
              AuthParam.COMPONENT_ACCESS_TOKEN, authorizationInfo.getAuthorizerAppId());
      // System.out.println(authorizerInfo);

      // Parse the qr code url from image.
      System.out.println(authorizerInfo.getQrCodeUrl());
      LuminanceSource source =
          new BufferedImageLuminanceSource(
              toBufferedImage(
                  ImageIO.read(new URL(authorizerInfo.getQrCodeUrl()))
                      .getScaledInstance(400, 400, Image.SCALE_SMOOTH)));
      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
      @SuppressWarnings("serial")
      Result qrCode =
          new MultiFormatReader()
              .decode(
                  bitmap,
                  new HashMap<DecodeHintType, Object>() {
                    {
                      put(DecodeHintType.CHARACTER_SET, "GBK");
                    }
                  });

      WxRestaurantDao.update(
          StaffDao.getAdminByRestaurant(restaurant.getId()),
          new WxRestaurant.UpdateBuilder()
              .setWeixinAppId(authorizerInfo.getAppId())
              .setWxSerial(authorizerInfo.getUserName())
              .setNickName(authorizerInfo.getNickName())
              .setHeadImgUrl(authorizerInfo.getHeadImg())
              .setQrCodeUrl(authorizerInfo.getQrCodeUrl())
              .setQrCode(qrCode.getText())
              .setQrCodeStatus(QrCodeStatus.NORMAL)
              .setRefreshToken(authorizationInfo.getAuthorizerRefreshToken()));

      AuthorizerToken authorizerToken =
          AuthorizerToken.newInstance(
              AuthParam.COMPONENT_ACCESS_TOKEN,
              authorizationInfo.getAuthorizerAppId(),
              authorizationInfo.getAuthorizerRefreshToken());

      // Make the menu.
      Menu menu = new Menu();
      Menu.delete(Token.newInstance(authorizerToken));
      menu.set1stButton(
          new Button.ClickBuilder("餐厅导航", WxHandleMessage.EventKey.NAVI_EVENT_KEY.getKey())
              .build());
      menu.set2ndButton(
          new Button.ScanMsgBuilder("扫一扫", WxHandleMessage.EventKey.SCAN_EVENT_KEY.getKey())
              .build());

      menu.set3rdButton(
          new Button.ClickBuilder("我的", "AAA")
              .addChild(
                  new Button.ClickBuilder(
                      "优惠活动", WxHandleMessage.EventKey.PROMOTION_EVENT_KEY.getKey()))
              .addChild(
                  new Button.ClickBuilder(
                      "我的订单", WxHandleMessage.EventKey.ORDER_EVENT_KEY.getKey()))
              .addChild(
                  new Button.ClickBuilder(
                      "我的会员卡", WxHandleMessage.EventKey.MEMBER_EVENT_KEY.getKey()))
              // .addChild(new Button.ClickBuilder("我的大转盘", WeiXinHandleMessage.ZHUAN_EVENT_KEY))
              .build());
      if (menu.create(Token.newInstance(authorizerToken)).isOk()) {
        response.getWriter().print(restaurant.getName() + "授权成功");
      } else {
        response.getWriter().print(restaurant.getName() + "授权失败");
      }

    } catch (BusinessException | SQLException e) {
      response.getWriter().print(e.getMessage());
    }

    return null;
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    final String pin = (String) request.getAttribute("pin");
    final String branchId = request.getParameter("branchId");
    final String beginDate = request.getParameter("beginDate");
    final String opening = request.getParameter("opening");
    final String ending = request.getParameter("ending");
    final String endDate = request.getParameter("endDate");
    final String orderID = request.getParameter("orderID");
    final String tableID = request.getParameter("tableID");
    final String deptID = request.getParameter("deptID");
    final String kitchenId = request.getParameter("kitchenID");
    final String queryType = request.getParameter("queryType");
    final String staffId = request.getParameter("staffID");
    final String isPaging = request.getParameter("isPaging");
    final String start = request.getParameter("start");
    final String limit = request.getParameter("limit");
    final String foodId = request.getParameter("foodId");
    final String regionId = request.getParameter("regionId");
    final String calcByDuty = request.getParameter("calcByDuty");
    final JObject jObject = new JObject();

    try {

      Staff staff = StaffDao.verify(Integer.parseInt(pin));

      if (branchId != null && !branchId.isEmpty() && Integer.parseInt(branchId) > 0) {
        staff = StaffDao.getAdminByRestaurant(Integer.parseInt(branchId));
      }

      List<OrderFood> list = null;

      if (queryType.equalsIgnoreCase("TodayByTbl")) {
        list = OrderFoodDao.getSingleDetailByTableId(staff, Integer.parseInt(tableID));
        if (orderID != null && !orderID.trim().isEmpty()) {
          final float totalPrice =
              OrderDao.getById(staff, Integer.parseInt(orderID), DateType.TODAY).calcTotalPrice();
          jObject.setExtra(
              new Jsonable() {

                @Override
                public JsonMap toJsonMap(int flag) {
                  JsonMap jm = new JsonMap();
                  jm.putFloat("detailTotalPrice", totalPrice);
                  return jm;
                }

                @Override
                public void fromJsonMap(JsonMap jsonMap, int flag) {}
              });
        }
      } else {
        final OrderFoodDao.ExtraCond extraCond;
        if (queryType.equalsIgnoreCase("today")) {
          extraCond = new OrderFoodDao.ExtraCond(DateType.TODAY);
        } else {
          extraCond = new OrderFoodDao.ExtraCond(DateType.HISTORY);
        }

        if (foodId != null && !foodId.isEmpty()) {
          extraCond.setFood(Integer.parseInt(foodId));
        }

        if (kitchenId != null && !kitchenId.isEmpty() && Integer.parseInt(kitchenId) > 0) {
          extraCond.setKitchen(Integer.parseInt(kitchenId));
        }

        if (regionId != null && !regionId.isEmpty() && Integer.parseInt(regionId) > 0) {
          extraCond.setRegionId(Region.RegionId.valueOf(Integer.parseInt(regionId)));
        }

        if (staffId != null && !staffId.isEmpty() && Integer.parseInt(staffId) > 0) {
          extraCond.setStaffId(Integer.parseInt(staffId));
        }

        if (beginDate != null && !beginDate.isEmpty() && endDate != null && !endDate.isEmpty()) {
          if (calcByDuty != null && !calcByDuty.isEmpty() && Boolean.parseBoolean(calcByDuty)) {
            DutyRange range = DutyRangeDao.exec(staff, beginDate, endDate);
            if (range != null) {
              extraCond.setDutyRange(range);
            } else {
              extraCond.setDutyRange(beginDate, endDate);
            }
          } else {
            extraCond.setDutyRange(beginDate, endDate);
          }
        }

        if (opening != null && !opening.isEmpty() && ending != null && !ending.isEmpty()) {
          HourRange range = new HourRange(opening, ending);
          extraCond.setHourRange(range);
        }

        if (deptID != null && !deptID.isEmpty() && !deptID.equals("-1")) {
          extraCond.setDeptId(DeptId.valueOf(Integer.parseInt(deptID)));
        }

        if (orderID != null && !orderID.isEmpty()) {
          extraCond.setOrder(Integer.parseInt(orderID));
        }

        list = OrderFoodDao.getSingleDetail(staff, extraCond, " ORDER BY OF.order_date ");
      }

      if (start != null && !start.isEmpty() && limit != null && !limit.isEmpty()) {
        list = DataPaging.getPagingData(list, Boolean.parseBoolean(isPaging), start, limit);
      }
      jObject.setRoot(list);

    } catch (BusinessException | SQLException e) {
      e.printStackTrace();
      jObject.initTip(e);

    } catch (Exception e) {
      e.printStackTrace();
      jObject.initTip4Exception(e);

    } finally {
      response.getWriter().print(jObject.toString());
    }

    return null;
  }