@Entity public class CommodityLocal implements Cloneable {
  private @Id Long id;
  private @Unique String objectId;
  private String category;
  private String name;
  private String details;
  private Integer cartCount;
  private Double price;
  private String CoverPhotoUrl;
  private Boolean CartIsChecked;

  @Generated(hash = 449135961)
  public CommodityLocal(Long id, String objectId, String category, String name, String details,
      Integer cartCount, Double price, String CoverPhotoUrl, Boolean CartIsChecked) {
    this.id = id;
    this.objectId = objectId;
    this.category = category;
    this.name = name;
    this.details = details;
    this.cartCount = cartCount;
    this.price = price;
    this.CoverPhotoUrl = CoverPhotoUrl;
    this.CartIsChecked = CartIsChecked;
  }

  @Generated(hash = 252057792) public CommodityLocal() {
  }

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getObjectId() {
    return this.objectId;
  }

  public void setObjectId(String objectId) {
    this.objectId = objectId;
  }

  public String getCategory() {
    return this.category;
  }

  public void setCategory(String category) {
    this.category = category;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getDetails() {
    return this.details;
  }

  public void setDetails(String details) {
    this.details = details;
  }

  public Integer getCartCount() {
    return this.cartCount;
  }

  public void setCartCount(Integer cartCount) {
    this.cartCount = cartCount;
  }

  public Double getPrice() {
    return this.price;
  }

  public void setPrice(Double price) {
    this.price = price;
  }

  public String getCoverPhotoUrl() {
    return this.CoverPhotoUrl;
  }

  public void setCoverPhotoUrl(String CoverPhotoUrl) {
    this.CoverPhotoUrl = CoverPhotoUrl;
  }

  public Boolean getCartIsChecked() {
    return this.CartIsChecked;
  }

  public void setCartIsChecked(Boolean CartIsChecked) {
    this.CartIsChecked = CartIsChecked;
  }
} public class CommodityOrder implements Serializable {

  private String objectId;
  private Double price;
  private Integer count;

  public CommodityOrder(String objectId, Double price, Integer count) {
    this.objectId = objectId;
    this.price = price;
    this.count = count;
  }

  public String getObjectId() {
    return objectId;
  }

  public void setObjectId(String objectId) {
    this.objectId = objectId;
  }

  public Double getPrice() {
    return price;
  }

  public void setPrice(Double price) {
    this.price = price;
  }

  public Integer getCount() {
    return count;
  }

  public void setCount(Integer count) {
    this.count = count;
  }
} public class KyUser extends BmobUser {
  private String pwdResumeQuestion;
  private String pwdResumeAnswer;
  private Boolean haveDetailInfo;

  public Boolean getHaveDetailInfo() {
    return haveDetailInfo;
  }

  public void setHaveDetailInfo(Boolean haveDetailInfo) {
    this.haveDetailInfo = haveDetailInfo;
  }

  public String getPwdResumeQuestion() {
    return pwdResumeQuestion;
  }

  public void setPwdResumeQuestion(String pwdResumeQuestion) {
    this.pwdResumeQuestion = pwdResumeQuestion;
  }

  public String getPwdResumeAnswer() {
    return pwdResumeAnswer;
  }

  public void setPwdResumeAnswer(String pwdResumeAnswer) {
    this.pwdResumeAnswer = pwdResumeAnswer;
  }
} public class Order extends BmobObject implements Serializable {
  public static final int NONE = 0;
  public static final int POSTED = 100;
  public static final int CONFIRMED = 110;

  public static final int COMPLETED = 200;

  public static final int CANCELLED = 500;
  public static final int DELETED = 600;
  private String userObjectId;
  private String username;
  private Integer status;

  private ReceiveAddress receiveAddress;
  private List<CommodityOrder> commodityList;

  private String name;
  private String phone;
  private String address;

  public Order() {
    status = POSTED;
  }

  public Order(List<CommodityOrder> commodityList) {
    this.commodityList = commodityList;
    status = POSTED;
  }

  /**
   * 设置收货地址以及当前用户信息
   */
  public void setAddressAndUserInfo(ReceiveAddress receiveAddress) {
    this.receiveAddress = receiveAddress;
    userObjectId = receiveAddress.getUserObjectId();
    username = receiveAddress.getUsername();

    name = receiveAddress.getName();
    phone = receiveAddress.getPhone();
    address = receiveAddress.getAddress();
    status = POSTED;
  }

  /**
   * JavaBean是否填写完整
   *
   * @return 填写完整的状态
   */
  public Boolean isDone() {
    if (userObjectId != null
        && username != null
        && receiveAddress != null
        && commodityList != null) {
      return true;
    }
    return false;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public Integer getStatus() {
    return status;
  }

  public void setStatus(Integer status) {
    this.status = status;
  }

  public ReceiveAddress getReceiveAddress() {
    return receiveAddress;
  }

  public void setReceiveAddress(ReceiveAddress receiveAddress) {
    this.receiveAddress = receiveAddress;
  }

  public String getUserObjectId() {
    return userObjectId;
  }

  public void setUserObjectId(String userObjectId) {
    this.userObjectId = userObjectId;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public List<CommodityOrder> getCommodityList() {
    return commodityList;
  }

  public void setCommodityList(List<CommodityOrder> commodityList) {
    this.commodityList = commodityList;
  }
} public class OrderActivity extends AppCompatActivity implements View.OnClickListener {
  private Context mContext;
  private ReceiveAddress receiveAddress;

  private Order order;
  private List<Commodity> commodities;

  private TextView name;
  private TextView phone;
  private TextView address;

  private View addressLayout;
  private RecyclerView recyclerView;
  private KyBaseRecyclerAdapter recyclerAdapter;
  private TextView tvPriceTotal;

  private Button btnOrderGeneration;
  private ToastUtil toastUtil;
  private Button btnCompleted;
  private Button btncancel;
  private View historyOrderInfoLayout;
  private View bottomNavigation;
  private OrderActivityPresenter presenter;
  private TextView orderStatus;
  private List<CommodityOrder> commodityOrderSubmitList;

  private int currentStatus;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order);
    mContext = this;
    presenter = new OrderActivityPresenter(this);
    toastUtil = new ToastUtil(mContext);

    historyOrderInfoLayout = findViewById(R.id.orderActivity_relativeLayout_historyOrderInfo);
    TextView orderId = (TextView) findViewById(R.id.orderActivity_historyOrderInfo_OrderId);
    TextView orderCreatedTime =
        (TextView) findViewById(R.id.orderActivity_historyOrderInfo_OrderCreatedTime);
    orderStatus = (TextView) findViewById(R.id.orderActivity_historyOrderInfo_orderStatus);

    addressLayout = findViewById(R.id.orderActivity_addressCardView);
    ImageView imageViewArrowRight =
        (ImageView) findViewById(R.id.orderActivity_addressCardView_ArrowRight);
    name = (TextView) findViewById(R.id.orderActivity_userName);
    phone = (TextView) findViewById(R.id.orderActivity_phone);
    address = (TextView) findViewById(R.id.orderActivity_address);

    recyclerView = (RecyclerView) findViewById(R.id.orderActivity_recycler_commodity);

    bottomNavigation = findViewById(R.id.orderActivity_bottomNavigation);
    tvPriceTotal = (TextView) findViewById(R.id.orderActivity_textview_total);
    btnOrderGeneration = (Button) findViewById(R.id.orderActivity_btn_orderGeneration);
    btnCompleted = (Button) findViewById(R.id.orderActivity_confirmCompleted);
    btncancel = (Button) findViewById(R.id.orderActivity_cancelOrder);

    KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.orderActivity_kyToolbar);
    kyToolBar.setNavigationOnClickListener(this);
    btnOrderGeneration.setOnClickListener(this);
    btnCompleted.setOnClickListener(this);
    btncancel.setOnClickListener(this);

    switchOrderLocation(OrderLocation.local);
    initRecyclerView();

    int requestCode = getIntent().getIntExtra("requestCode", -1);
    KLog.d("requestCode" + requestCode);
    currentStatus = requestCode;
    switch (requestCode) {
      case KySet.CART_REQUEST_SUBMIT_ORDER:
        bottomNavigation.setVisibility(View.VISIBLE);
        btnOrderGeneration.setVisibility(View.VISIBLE);
        imageViewArrowRight.setVisibility(View.VISIBLE);
        addressLayout.setVisibility(View.VISIBLE);
        addressLayout.setOnClickListener(this);
        queryDefaultAddressFromBmob();
        break;
      case KySet.USER_REQUEST_HISTORY_ORDER:
        historyOrderInfoLayout.setVisibility(View.VISIBLE);
        bottomNavigation.setVisibility(View.VISIBLE);
        orderId.setText(order.getObjectId());
        orderCreatedTime.setText(order.getCreatedAt());
        changeOrderStatus(order);
        name.setText(order.getName());
        phone.setText(order.getPhone());
        address.setText(order.getAddress());
        break;
      default:
        finish();
        break;
    }
    initRecyclerOrderData(order.getCommodityList());
  }

  /**
   * 根据不同的订单状态改变界面显示
   */
  public void changeOrderStatus(Order order) {
    this.order = order;

    switch (order.getStatus()) {
      case Order.POSTED:
        orderStatus.setText("订单已确认");
        orderStatus.setTextColor(mContext.getResources().getColor(R.color.red));
        btnCompleted.setVisibility(View.VISIBLE);
        btncancel.setVisibility(View.VISIBLE);
        break;
      case Order.CONFIRMED:
        orderStatus.setText("商品已送达");
        orderStatus.setTextColor(mContext.getResources().getColor(R.color.blue));
        btnCompleted.setVisibility(View.VISIBLE);
        btncancel.setVisibility(View.INVISIBLE);
        break;
      case Order.COMPLETED:
        orderStatus.setText("订单已完成");
        orderStatus.setTextColor(mContext.getResources().getColor(R.color.green));
        btnCompleted.setVisibility(View.INVISIBLE);
        btncancel.setVisibility(View.INVISIBLE);
        break;
      case Order.CANCELLED:
        orderStatus.setText("订单已取消");
        orderStatus.setTextColor(mContext.getResources().getColor(R.color.gray));
        btnCompleted.setVisibility(View.INVISIBLE);
        btncancel.setVisibility(View.INVISIBLE);
        break;
    }
  }

  /**
   * 选择 Order 对象所处的位置并获取所需的 Order 对象
   *
   * @param orderLocation Order 对象所处的位置
   */
  private void switchOrderLocation(OrderLocation orderLocation) {
    switch (orderLocation) {
      case local:
        Bundle bundle = getIntent().getBundleExtra("bundle");
        Order order = (Order) bundle.getSerializable("order");
        initOrder(order);
        break;
      case bmob:
        queryCurrentOrderFromBmob();
        break;
    }
  }

  /**
   * 分析获得的Order对象，进行必要的初始化
   *
   * @param order Order对象
   */
  private void initOrder(Order order) {
    String userObjectId = order.getUserObjectId();
    String userName = order.getUsername();

    if (userObjectId != null && userName != null) {
      this.order = order;
    } else {
      Intent intent = new Intent();
      intent.putExtra("message", "请求的JavaBean(Order)内容不完整");
      setResult(KySet.RESULT_ERROR, intent);
      finish();
    }
  }

  private void queryDefaultAddressFromBmob() {
    BmobQuery<ReceiveAddress> bmobQuery = new BmobQuery<>();
    bmobQuery.addWhereEqualTo("userObjectId", order.getUserObjectId());
    bmobQuery.addWhereEqualTo("isDefault", true);
    bmobQuery.setLimit(50);
    bmobQuery.findObjects(new FindListener<ReceiveAddress>() {

      @Override public void done(List<ReceiveAddress> list, BmobException e) {
        if (e != null) {
          toastUtil.show(e.getMessage());
          return;
        }
        if (list.size() > 0) {
          receiveAddress = list.get(0);
          name.setText(receiveAddress.getName());
          phone.setText(receiveAddress.getPhone());
          address.setText(receiveAddress.getAddress());
        }
      }
    });
  }

  /**
   *
   */
  private void queryCurrentOrderFromBmob() {
    BmobQuery<Order> bmobQuery = new BmobQuery<>();
    bmobQuery.addWhereEqualTo("objectId", order.getObjectId());
    bmobQuery.findObjects(new FindListener<Order>() {

      @Override public void done(List<Order> list, BmobException e) {
        if (e != null) {
          toastUtil.show(e.getMessage());
          return;
        }
        if (list.size() > 0) {
          order = list.get(0);
          initOrder(order);
        }
      }
    });
  }

  private void initRecyclerView() {
    if (recyclerAdapter == null) {
      initRecyclerAdapter(new ArrayList<Commodity>());
    }
    recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(
        new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    recyclerView.setAdapter(recyclerAdapter);
  }

  private void initRecyclerOrderData(List<CommodityOrder> commodityOrders) {
    //用于从服务器请求得到的商品信息
    commodities = new ArrayList<>();
    //用于提交到服务器中的订单中的商品信息
    commodityOrderSubmitList = new ArrayList<>();

    for (final CommodityOrder commodityOrder : commodityOrders) {
      BmobQuery<Commodity> bmobQuery = new BmobQuery<>();
      bmobQuery.getObject(commodityOrder.getObjectId(), new QueryListener<Commodity>() {
        @Override public void done(Commodity commodity, BmobException e) {
          if (e != null) {
            KLog.d("有异常：" + e.getMessage());
            return;
          }
          if (commodity.getCount() <= 0 && currentStatus == KySet.CART_REQUEST_SUBMIT_ORDER) {
            return;
          }
          KLog.d("读取成功，objectId：" + commodity.getObjectId() + "," + commodity.getName());
          commodity.setCount(commodityOrder.getCount());
          commodities.add(commodity);
          commodityOrderSubmitList.add(commodityOrder);
          recyclerAdapter.reloadData(commodities);
          countTotalPrices();
        }
      });
    }
  }

  /**
   * 计算并显示已勾选商品的总价
   */
  public void countTotalPrices() {
    double priceTotal = 0;
    if (commodities != null && commodities.size() > 0) {
      for (Commodity commodityLocal : commodities) {
        int count = commodityLocal.getCount();
        double price = commodityLocal.getPrice();
        priceTotal = priceTotal + price * count;
      }
    }
    tvPriceTotal.setText("合计： " + priceTotal + "元");
  }

  public void initRecyclerAdapter(List<Commodity> list) {
    recyclerAdapter =
        new KyBaseRecyclerAdapter<Commodity>(list, R.layout.recycler_orderactivity_show) {
          @Override
          public void setDataToViewHolder(final Commodity dataItem, KyBaseViewHolder holder) {
            holder.getSimpleDraweeView(R.id.recycler_orderActivity_draweeview)
                .setImageURI(Uri.parse(dataItem.getCoverPhotoUrl()));
            holder.getTextView(R.id.recycler_orderActivity_text_title).setText(dataItem.getName());
            holder.getTextView(R.id.recycler_orderActivity_text_price)
                .setText(dataItem.getPrice().toString() + " 元");
            holder.getTextView(R.id.recycler_orderActivity_text_count)
                .setText("X " + dataItem.getCount());
          }
        };
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {

      //导航栏返回
      case R.id.kytoolbar_navigation:
        finish();
        break;

      //收货地址信息CardView，设置收货地址
      case R.id.orderActivity_addressCardView:
        KLog.d("激活");
        Intent intent = new Intent(mContext, AddressOptionActivity.class);
        intent.putExtra("requestCode", KySet.CART_REQUEST_SELECT_RECEIVE_ADDRESS);
        intent.putExtra("userName", order.getUsername());
        intent.putExtra("objectId", order.getUserObjectId());
        startActivityForResult(intent, KySet.CART_REQUEST_SELECT_RECEIVE_ADDRESS);
        break;

      //生成订单按钮
      case R.id.orderActivity_btn_orderGeneration:
        if (receiveAddress != null) {
          btnOrderGeneration.setEnabled(false);
          if (commodityOrderSubmitList.size() <= 0) {
            toastUtil.show("您选择的商品可能被抢光了, 请重新选择");
            return;
          }
          //生成用于提交服务器的新的Order对象
          Order orderSubmit = new Order(commodityOrderSubmitList);
          orderSubmit.setAddressAndUserInfo(receiveAddress);
          if (orderSubmit.isDone()) {
            KLog.d("已上传服务器:" + orderSubmit.getCommodityList().size());
            orderSubmit.save(new SaveListener<String>() {
              @Override public void done(String objectId, BmobException e) {
                if (e == null) {
                  Intent intentResult = new Intent();
                  Bundle bundle = new Bundle();
                  order.setObjectId(objectId);
                  bundle.putSerializable("order", order);
                  intentResult.putExtra("bundle", bundle);
                  setResult(KySet.CART_RESULT_SUBMIT_ORDER, intentResult);
                  finish();
                } else {
                  btnOrderGeneration.setEnabled(true);
                  toastUtil.show("订单生成失败,请重试");
                }
              }
            });
          }
        } else {
          toastUtil.show("请先点击上方的标签添加收货地址");
        }
        break;
      case R.id.orderActivity_confirmCompleted:
        setResult(KySet.USER_RESULT_REFRESH_ORDER);
        presenter.updateOrderStatus(order, Order.COMPLETED);
        break;
      case R.id.orderActivity_cancelOrder:
        setResult(KySet.USER_RESULT_REFRESH_ORDER);
        presenter.updateOrderStatus(order, Order.CANCELLED);
        break;
    }
  }

  public void showMessage(String message) {
    toastUtil.show(message);
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (resultCode) {
      case KySet.CART_RESULT_SELECT_RECEIVE_ADDRESS:
        ReceiveAddress receiveAddress = (ReceiveAddress) data.getSerializableExtra("address");
        if (receiveAddress != null) {
          this.receiveAddress = receiveAddress;
          name.setText(receiveAddress.getName());
          phone.setText(receiveAddress.getPhone());
          address.setText(receiveAddress.getAddress());
        }
        break;
    }
  }

  enum OrderLocation {
    local,
    bmob
  }
} public class GreenDaoKyHelper {

  private static DaoSession daoSession;

  static void init(DaoMaster.DevOpenHelper helper) {
    // do this once, for example in your Application class
    QueryBuilder.LOG_SQL = BuildConfig.BITKY_LOG_DEBUG;
    QueryBuilder.LOG_VALUES = BuildConfig.BITKY_LOG_DEBUG;

    SQLiteDatabase db = helper.getWritableDatabase();
    DaoMaster daoMaster = new DaoMaster(db);
    daoSession = daoMaster.newSession();
  }

  public static DaoSession getDaoSession() {
    if (daoSession != null) {
      return daoSession;
    } else {
      throw new NullPointerException("未初始化DaoSession");
    }
  }

  /**
   * 更新数据库中商品被选中的状态
   * @param c 数据库中的商品
   */
  public static void updateChecked(CommodityLocal c) {
    CommodityLocalDao commodityLocalDao = GreenDaoKyHelper.getDaoSession().getCommodityLocalDao();
    commodityLocalDao.update(c);
  }

  /**
   * 在[本地数据库]购物车中插入商品或增加其数量
   *
   * @param c 商品bean
   */
  public static void insertOrIncrease(Commodity c) {
    CommodityLocalDao commodityLocalDao = GreenDaoKyHelper.getDaoSession().getCommodityLocalDao();
    QueryBuilder<CommodityLocal> queryBuilder = commodityLocalDao.queryBuilder();
    queryBuilder.where(CommodityLocalDao.Properties.ObjectId.eq(c.getObjectId()));
    List<CommodityLocal> localList = queryBuilder.list();
    KLog.d("查询到的结果数:" + localList.size());
    CommodityLocal commodityLocal =
        new CommodityLocal(null, c.getObjectId(), c.getCategory(), c.getName(), c.getDetails(), 1,
            c.getPrice(), c.getCoverPhotoUrl(), false);
    if (localList.size() >= 1) {
      commodityLocal.setId(localList.get(0).getId());
      commodityLocal.setCartCount(localList.get(0).getCartCount() + 1);
      commodityLocalDao.update(commodityLocal);
    } else {
      commodityLocalDao.insert(commodityLocal);
    }
  }

  /**
   * 查询[本地数据库]购物车中的所有商品
   *
   * @return 查询到的所有商品
   */
  public static List<CommodityLocal> queryAll() {
    CommodityLocalDao commodityLocalDao = GreenDaoKyHelper.getDaoSession().getCommodityLocalDao();
    QueryBuilder<CommodityLocal> queryBuilder = commodityLocalDao.queryBuilder();
    return queryBuilder.list();
  }

  public static void deleteItem(CommodityLocal dataItem) {
    CommodityLocalDao commodityLocalDao = GreenDaoKyHelper.getDaoSession().getCommodityLocalDao();
    commodityLocalDao.delete(dataItem);
  }

  public static void deleteItems(List<CommodityLocal> dataItems) {
    if (dataItems == null || dataItems.size() == 0) return;
    CommodityLocalDao commodityLocalDao = GreenDaoKyHelper.getDaoSession().getCommodityLocalDao();
    commodityLocalDao.deleteInTx(dataItems);
  }
} public class ToastUtil {
  private Context mContext;
  private SuperToast mSuperToast;
  int i = 1;
  String msg = "";

  public ToastUtil(Context context) {
    this(context, null);
  }

  public ToastUtil(Context context, Type type) {
    mContext = context;
    if (type == null) assignFlyBlue();
    if (type == Type.FlyBlue) assignFlyBlue();
  }

  public ToastUtil assignFlyBlue() {
    if (mSuperToast == null) {
      mSuperToast = SuperActivityToast.create(mContext, new Style(), Style.TYPE_STANDARD)
          .setText("New BitkyToast");
      mSuperToast.setDuration(Style.DURATION_VERY_SHORT)
          .setFrame(Style.FRAME_STANDARD)
          .setAnimations(Style.ANIMATIONS_FLY)
          .setColor(0xcc1e90ff);
    }
    return this;
  }

  public void show(String msg) {
    if (mSuperToast == null) {
      KLog.w("对象未实例化");
    } else {
      if (!this.msg.equals(msg)) {
        this.msg = msg;
        mSuperToast.setText(msg).show();
      } else if (!mSuperToast.isShowing()) {
        mSuperToast.setText(msg).show();
      }
    }
  }

  enum Type {
    FlyBlue
  }
} public class DividerItemDecoration extends RecyclerView.ItemDecoration {
  /*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

  private static final int[] ATTRS = new int[] {
      android.R.attr.listDivider
  };

  public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

  public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

  private Drawable mDivider;

  private int mOrientation;

  public DividerItemDecoration(Context context, int orientation) {
    final TypedArray a = context.obtainStyledAttributes(ATTRS);
    mDivider = a.getDrawable(0);
    a.recycle();
    setOrientation(orientation);
  }

  public void setOrientation(int orientation) {
    if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
      throw new IllegalArgumentException("invalid orientation");
    }
    mOrientation = orientation;
  }

  @Override public void onDraw(Canvas c, RecyclerView parent) {
    if (mOrientation == VERTICAL_LIST) {
      drawVertical(c, parent);
    } else {
      drawHorizontal(c, parent);
    }
  }

  public void drawVertical(Canvas c, RecyclerView parent) {
    final int left = parent.getPaddingLeft();
    final int right = parent.getWidth() - parent.getPaddingRight();

    final int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
      final View child = parent.getChildAt(i);
      final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
      final int top = child.getBottom() + params.bottomMargin;
      final int bottom = top + mDivider.getIntrinsicHeight();
      mDivider.setBounds(left, top, right, bottom);
      mDivider.draw(c);
    }
  }

  public void drawHorizontal(Canvas c, RecyclerView parent) {
    final int top = parent.getPaddingTop();
    final int bottom = parent.getHeight() - parent.getPaddingBottom();

    final int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
      final View child = parent.getChildAt(i);
      final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
      final int left = child.getRight() + params.rightMargin;
      final int right = left + mDivider.getIntrinsicHeight();
      mDivider.setBounds(left, top, right, bottom);
      mDivider.draw(c);
    }
  }

  @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
    if (mOrientation == VERTICAL_LIST) {
      outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    } else {
      outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
    }
  }
} public class KyBmobHelper {

  /**
   * 获取本地保存的当前用户
   */
  public static KyUser getCurrentUser() {
    return BmobUser.getCurrentUser(KyUser.class);
  }


} public class KySet {
  //请求
  public static final int USER_REQUEST_SIGN_UP = 11;
  public static final int USER_REQUEST_LOG_IN = 12;
  public static final int CART_REQUEST_SUBMIT_ORDER = 13;
  public static final int USER_REQUEST_CREATE_ADDRESS = 14;
  public static final int CART_REQUEST_SELECT_RECEIVE_ADDRESS = 15;
  public static final int USER_REQUEST_HISTORY_ORDER = 16;
  public static final int USER_REQUEST_PHONE_SIGNUP_OR_LOGIN = 18;

  //返回结果
  public static final int USER_RESULT_SIGN_UP = 21;
  public static final int USER_RESULT_LOG_IN = 22;
  public static final int CART_RESULT_SUBMIT_ORDER = 23;
  public static final int USER_RESULT_CREATE_ADDRESS = 24;
  public static final int CART_RESULT_SELECT_RECEIVE_ADDRESS = 25;
  public static final int USER_RESULT_REFRESH_ORDER = 27;
  public static final int USER_RESULT_PHONE_SIGNUP_OR_LOGIN = 28;

  public static final int RESULT_ERROR = -21;
} public class ItemCounter extends LinearLayout implements View.OnClickListener {

  private LayoutInflater inflater;
  private Button buttonAdd;
  private Button buttonMinus;
  private TextView textViewShow;

  private int value = 1;
  private int valueMax = 99;
  private int valueMin = 1;

  OnCounterOverflowListener overflowListener;
  OnCounterClickListener counterClickListener;

  public ItemCounter(Context context) {
    this(context, null);
  }

  public ItemCounter(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public ItemCounter(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    inflater = LayoutInflater.from(context);

    View view = inflater.inflate(R.layout.widget_item_counter, this, true);

    buttonAdd = (Button) view.findViewById(R.id.btnAdd_widget_itemCounter);
    buttonMinus = (Button) view.findViewById(R.id.btnMinus_widget_itemCounter);
    textViewShow = (TextView) view.findViewById(R.id.textViewShow_widget_itemCounter);
    textViewShow.setText(value + "");
    buttonAdd.setOnClickListener(this);
    buttonMinus.setOnClickListener(this);

    //if (attrs != null) {
    //  TintTypedArray typedArray =
    //      TintTypedArray.obtainStyledAttributes(context, attrs, R.styleable.ItemCounter,
    //          defStyleAttr, 0);
    //
    //  typedArray.recycle();
    //}
  }

  public void setOnCounterOverflowListener(OnCounterOverflowListener overflowListener) {
    this.overflowListener = overflowListener;
  }

  public void setOnCounterClickListener(OnCounterClickListener counterClickListener) {
    this.counterClickListener = counterClickListener;
  }

  public int getValue() {
    return value;
  }

  public void setValue(int value) {
    this.value = value;
    textViewShow.setText(value + "");
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.btnAdd_widget_itemCounter:
        if (value < valueMax) {
          value++;
          textViewShow.setText(value + "");
          if (counterClickListener != null) {
            counterClickListener.OnButtonClick(value, ButtonType.add);
          }
        } else {
          if (overflowListener != null) overflowListener.addOverflow();
        }
        break;

      case R.id.btnMinus_widget_itemCounter:
        if (value > valueMin) {
          value--;
          textViewShow.setText(value + "");
          if (counterClickListener != null) {
            counterClickListener.OnButtonClick(value, ButtonType.minus);
          }
        } else {
          if (overflowListener != null) overflowListener.minusOverflow();
        }
        break;
    }
  }

  public enum ButtonType {
    add,
    minus
  }

  public interface OnCounterClickListener {

    void OnButtonClick(int currentCount, ButtonType type);
  }

  public interface OnCounterOverflowListener {

    void addOverflow();

    void minusOverflow();
  }
}
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import cc.bitky.bitkyshop.R;
import cc.bitky.bitkyshop.bean.cart.CommodityLocal;
import cc.bitky.bitkyshop.bean.cart.CommodityOrder;
import cc.bitky.bitkyshop.bean.cart.KyUser;
import cc.bitky.bitkyshop.bean.cart.Order;
import cc.bitky.bitkyshop.fragment.userfragment.orderactivity.OrderActivity;
import cc.bitky.bitkyshop.globalDeploy.GreenDaoKyHelper;
import cc.bitky.bitkyshop.utils.ToastUtil;
import cc.bitky.bitkyshop.utils.recyclerview.DividerItemDecoration;
import cc.bitky.bitkyshop.utils.tools.KyBmobHelper;
import cc.bitky.bitkyshop.utils.tools.KySet;
import cc.bitky.bitkyshop.utils.widget.ItemCounter;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
    btnDeleteAll = (Button) view.findViewById(R.id.cartfragment_btn_deleteAll);
    btnDeleteAll.setOnClickListener(this);
    btnOrderAll = (Button) view.findViewById(R.id.cartfragment_btn_order);
    btnOrderAll.setOnClickListener(this);
  }

  /**
   * 从本地数据库中读取数据并初始化RecyclerView
   */
  private void initRecyclerView() {
    commodityLocals = GreenDaoKyHelper.queryAll();
    KLog.d("本地数据库，commodityLocals:" + commodityLocals.size());
    if (recyclerAdapter != null) {
      recyclerAdapter.showItemDeleteButton(false);
      recyclerAdapter.reloadData(commodityLocals);
    } else {
      recyclerAdapter = new CartRecyclerAdapter(commodityLocals);
      recyclerAdapter.setOnCheckboxListener(new CartRecyclerAdapter.CheckboxListener() {
        @Override public void OnClick(CheckBox v) {
          countTotalPrices();
          updateCheckedAll();
        }
      });
      recyclerAdapter.setOnItemCounterListener(new CartRecyclerAdapter.ItemCounterListener() {
        @Override public void addOverflow() {
          KLog.d("addOverflow()");
        }

        @Override public void minusOverflow() {
          KLog.d("minusOverflow()");
        }

        @Override public void OnButtonClick(int currentCount, ItemCounter.ButtonType type) {
          countTotalPrices();
        }
      });
      recyclerAdapter.setOnDeleteItemListener(new CartRecyclerAdapter.DeleteItemListener() {
        @Override public void OnClick(CommodityLocal dataItem) {
          GreenDaoKyHelper.deleteItem(dataItem);
          countTotalPrices();
          updateCheckedAll();
        }
      });
    }
    RecyclerView recyclerViewCategray =
        (RecyclerView) view.findViewById(R.id.recyclerView_cartFragment);
    recyclerViewCategray.setAdapter(recyclerAdapter);
    recyclerViewCategray.setLayoutManager(new LinearLayoutManager(mContext));
    recyclerViewCategray.setItemAnimator(new DefaultItemAnimator());
    recyclerViewCategray.addItemDecoration(
        new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
  }

  private void itemSetIsChecked(Boolean isChecked) {
    if (commodityLocals != null) {
      for (CommodityLocal commodityLocal : commodityLocals) {
        commodityLocal.setCartIsChecked(isChecked);
        GreenDaoKyHelper.updateChecked(commodityLocal);
      }
    }
    if (recyclerAdapter != null) recyclerAdapter.notifyDataSetChanged();
  }

  /**
   * 更新全选复选框的状态
   */
  private void updateCheckedAll() {
    Boolean isCheckedAll = true;
    if (commodityLocals == null || commodityLocals.size() == 0) {
      isCheckedAll = false;
    } else {
      for (CommodityLocal commodityLocal : commodityLocals) {
        if (!commodityLocal.getCartIsChecked()) {
          isCheckedAll = false;
          break;
        }
      }
    }
    KLog.d("isCheckedAll+" + isCheckedAll);
    checkBoxAll.setChecked(isCheckedAll);
  }

  /**
   * 计算并显示已勾选商品的总价
   */
  public void countTotalPrices() {
    double priceTotal = 0;
    if (commodityLocals != null && commodityLocals.size() > 0) {
      for (CommodityLocal commodityLocal : commodityLocals) {
        if (!commodityLocal.getCartIsChecked()) continue;
        int count = commodityLocal.getCartCount();
        double price = commodityLocal.getPrice();
        priceTotal = priceTotal + price * count;
      }
    }
    textViewTotalPrice.setText("合计： " + priceTotal + "元");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (resultCode) {
      case KySet.CART_RESULT_SUBMIT_ORDER:
        toastUtil.show("添加订单成功");
        btnDeleteAll.performClick();
        break;
    }
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.cartfragment_checkbox_all:
        itemSetIsChecked(checkBoxAll.isChecked());
        countTotalPrices();
        break;
      case R.id.cartfragment_btn_deleteAll:
        GreenDaoKyHelper.deleteItems(recyclerAdapter.deleteCheckedItem());
        checkBoxAll.setChecked(false);
        countTotalPrices();
        break;
      case R.id.cartfragment_btn_order:
        KyUser kyUser = KyBmobHelper.getCurrentUser();