/**
   * 淘客api请求的方法
   *
   * @param keyword 关键字 (如果是全部,则为cid = 0);
   * @param sort 排序规则 sort String 可选 price_desc 默认排序:default price_desc(价格从高到低) price_asc(价格从低到高)
   *     credit_desc(信用等级从高到低) commissionRate_desc(佣金比率从高到低) commissionRate_asc(佣金比率从低到高)
   *     commissionNum_desc(成交量成高到低) commissionNum_asc(成交量从低到高) commissionVolume_desc(总支出佣金从高到低)
   *     commissionVolume_asc(总支出佣金从低到高) delistTime_desc(商品下架时间从高到低) delistTime_asc(商品下架时间从低到高)
   * @param isFromTmall 是否请求天猫的数据
   * @param isAll 是否请求的全部数据
   * @param page_no 请求的页数
   */
  private void seachTaobaokeFromKeyWord(
      String keyword, String sort, boolean isFromTmall, boolean isAll, final int page_no) {
    sharedPreferences = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
    long userId = sharedPreferences.getLong("userId", 10000);
    AccessToken accessToken = TopConfig.client.getAccessToken(userId);
    String tql = "";
    Map<String, String> params = new HashMap<String, String>();
    if (isAll) {
      params.put("cid", keyword);
    } else {
      params.put("keyword", keyword);
    }
    params.put("page_size", Integer.toString(pageSize)); // 最大40个,
    params.put("page_no", Integer.toString(page_no)); // 最多10页
    params.put("mall_item", isFromTmall + "");
    params.put("sort", sort);
    tql = TqlHelper.generateTaoBaoKeTql(SearchItem.class, params);
    if (BuildConfig.DEBUG) {
      System.out.println(tql);
    }
    headProgressBar.setVisibility(View.VISIBLE);
    GetTopData.getDataFromTop(
        tql,
        new SearchItemParser(),
        userId,
        new MyTqlListener() {
          @Override
          public void onComplete(Object result) {
            headProgressBar.setVisibility(View.GONE);
            ArrayList<SearchItem> results = (ArrayList) result;
            if (results != null && results.size() > 0) {
              if (!TextUtils.isEmpty(card)) {
                String money = card.replace(" 元", "");
                Integer mon = Integer.parseInt(money.trim());
                resultMap = new HashMap<String, SearchItem>();
                for (int i = 0; i < results.size(); i++) {
                  String reg = "\\d+\\.\\d+";
                  Pattern pattern = Pattern.compile(reg);
                  String resultPrice = results.get(i).getPrice().replace("\\'", "");
                  LogUtil.i(TAG, "price" + results.get(i).getPrice());
                  Matcher matcher = pattern.matcher(resultPrice);
                  if (matcher.find()) {
                    resultPrice = matcher.group();
                    if (mon == 30) {
                      if ((mon - Float.parseFloat(resultPrice)) < 5) {
                        LogUtil.i(
                            TAG, Float.parseFloat(resultPrice) + "  Float.parseFloat(resultPrice)");
                        LogUtil.i(
                            TAG,
                            mon
                                - Float.parseFloat(resultPrice)
                                + "  mon-Float.parseFloat(resultPrice)");
                        Toast.makeText(getActivity(), resultPrice, 1).show();
                        resultMap = new HashMap<String, SearchItem>();
                        resultMap.put(RechargeFragment.this.q, results.get(i));
                        Float cheap = (mon - Float.parseFloat(resultPrice)) / mon;
                        String cheapString = String.format("%.5f", cheap);
                        priceTextView.setText(resultPrice + " 元" + " 为您节省" + cheapString + "%");
                        break;
                      }
                    } else {
                      if ((mon - Float.parseFloat(resultPrice)) < 10) {
                        LogUtil.i(
                            TAG, Float.parseFloat(resultPrice) + "  Float.parseFloat(resultPrice)");
                        LogUtil.i(
                            TAG,
                            mon
                                - Float.parseFloat(resultPrice)
                                + "  mon-Float.parseFloat(resultPrice)");
                        Toast.makeText(getActivity(), resultPrice, 1).show();
                        resultMap = new HashMap<String, SearchItem>();
                        resultMap.put(RechargeFragment.this.q, results.get(i));
                        Float cheap = (mon - Float.parseFloat(resultPrice)) / mon;
                        String cheapString = String.format("%.5f", cheap);
                        priceTextView.setText(resultPrice + " 元" + " 为您节省" + cheapString + "%");
                        break;
                      }
                    }
                  }
                }
              }
            }
            if (BuildConfig.DEBUG) {
              if (results != null) {
                Log.i(TAG, Integer.toString(results.size()));
              }
            }
          }

          @Override
          public void onException(Exception e) {
            headProgressBar.setVisibility(View.GONE);
            AppException.network(e).makeToast(getActivity());
          }

          @Override
          public void onResponseException(Object apiError) {
            headProgressBar.setVisibility(View.GONE);
            Toast.makeText(getActivity(), ((ApiError) apiError).getMsg(), 0).show();
            if (BuildConfig.DEBUG) {
              Log.i(TAG, apiError.toString());
            }
          }
        });
  }
  /**
   * @param q 表示搜索的关键字,例如搜索query=nike。 当输入关键字为中文时,将对他进行URLEncode的UTF-8格式编码,如
   *     耐克,那么q=%E8%80%90%E5%85%8B。
   * @param sort 排序类型。类型包括: s: 人气排序 p: 价格从低到高; pd: 价格从高到低; d: 月销量从高到低; td: 总销量从高到低; pt: 按发布时间排序.
   * @param cat 前台类目id,目前其他接口无法获取, 只能自己去寻找。建议使用关键字获取数据。支持多选过滤,cat=catid1,catid2。
   * @param start 可以用该字段来实现分页功能。表示查询起始位置, 默认从第0条开始,start=10,表示从第10条数据开始查询,start不得大于1000。
   */
  private void getFromTmallByKeyWords(String q, String sort, String cat, final int pageNo) {

    long userId = sharedPreferences.getLong("userId", 10000);
    AccessToken accessToken = TopConfig.client.getAccessToken(userId);
    String tql = "";
    /*
     * if (userId == 0l || accessToken == null) { Toast t =
     * Toast.makeText(ProductsActivity.this, "请先授权", Toast.LENGTH_SHORT);
     * t.show(); client.authorize(ProductsActivity.this); return; }
     */
    /**
     * select num_iid,title,click_url from taobao.taobaoke.widget.items.convert where num_iids in
     * (select item_id from tmall.items.discount.search where q = %e6%89%8b%e6%9c%ba )
     */
    List<String> fields = new ArrayList<String>();
    fields.add("item_id");
    Map<String, String> params = new HashMap<String, String>();
    // params.put("q", "%e6%89%8b%e6%9c%ba");
    if (!TextUtils.isEmpty(q)) {
      params.put("q", Uri.encode(q));
    }
    if (!TextUtils.isEmpty(cat)) {
      params.put("cat", cat);
    }
    if (TextUtils.isEmpty(q) & TextUtils.isEmpty(cat)) {
      throw new RuntimeException("关键字q和前台类目不能同时为空!");
    }
    int start = pageNo * pageSize;
    params.put("start", Integer.toString(start)); // 最多1000页
    params.put("sort", sort);
    String tmallTql = TqlHelper.generateTMallTql(fields, params);
    tql = TqlHelper.generateTMallConvertToTaoKenestTql(SearchItem.class, "num_iids", tmallTql);
    System.out.println(tql);

    GetTopData.getDataFromTop(
        tql,
        new TmallToTaokeItemParser(),
        userId,
        new MyTqlListener() {
          @Override
          public void onResponseException(Object apiError) {

            Toast.makeText(getActivity(), ((ApiError) apiError).getMsg(), 0).show();
            if (BuildConfig.DEBUG) {
              Log.i(TAG, apiError.toString());
            }
          }

          @Override
          public void onException(Exception e) {
            AppException.network(e).makeToast(getActivity());
          }

          @Override
          public void onComplete(Object result) {
            // TODO Auto-generated method stub
            ArrayList<SearchItem> results = (ArrayList) result;
            if (results != null && results.size() > 0) {
              if (!TextUtils.isEmpty(card)) {
                String money = card.replace(" 元", "");
                Integer mon = Integer.parseInt(money.trim());
                resultMap = new HashMap<String, SearchItem>();
                for (int i = 0; i < results.size(); i++) {
                  String reg = "\\d+";
                  Pattern pattern = Pattern.compile(reg);
                  String resultPrice = results.get(i).getPrice().replace("\\'", "");
                  Matcher matcher = pattern.matcher(resultPrice);
                  if (matcher.find()) {
                    resultPrice = matcher.group();
                    if ((mon - Float.parseFloat(resultPrice)) < 10) {
                      LogUtil.i(
                          TAG, Float.parseFloat(resultPrice) + "  Float.parseFloat(resultPrice)");
                      LogUtil.i(
                          TAG,
                          mon
                              - Float.parseFloat(resultPrice)
                              + "  mon-Float.parseFloat(resultPrice)");
                      Toast.makeText(getActivity(), resultPrice, 1).show();
                      resultMap = new HashMap<String, SearchItem>();
                      resultMap.put(RechargeFragment.this.q, results.get(i));
                      java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
                      float cheap = (mon - Float.parseFloat(resultPrice)) / mon;
                      df.format(cheap);
                      priceTextView.setText(resultPrice + " 元" + "  为您节省" + cheap + "%");
                      break;
                    }
                  }
                }
              }
            }
            if (BuildConfig.DEBUG) {
              if (results != null) {
                Log.i(TAG, Integer.toString(results.size()));
              }
            }
          }
        });
  }