wpc
2018-11-27 680fbc9e73da3e11988557cf88fd935efd3e0b1e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package com.haicaojie.android.ui.main;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.haicaojie.android.BasicTextHttpResponseHandler;
import com.haicaojie.android.BuXinConstant;
import com.haicaojie.android.R;
import com.haicaojie.android.ShoppingApi;
import com.haicaojie.android.entity.FirstCategory;
import com.haicaojie.android.entity.HomeBanner;
import com.haicaojie.android.entity.RecommendGoods;
import com.haicaojie.android.entity.SpecialOffer;
import com.haicaojie.android.entity.SpecialOffer2;
import com.haicaojie.android.entity.TaoBaoGoodsBrief;
import com.haicaojie.android.ui.*;
import com.haicaojie.android.ui.category.CategoryTypeActivity;
import com.haicaojie.android.ui.recommend.CaptureActivity;
import com.haicaojie.android.ui.recommend.GoodsBrowserActivity;
import com.haicaojie.android.ui.recommend.RecommendCategoryFragment;
import com.haicaojie.android.ui.recommend.RecommendFragment;
import com.haicaojie.android.ui.recommend.SearchActivity;
import com.haicaojie.android.util.zxing.bean.ZxingConfig;
import com.haicaojie.android.util.zxing.common.Constant;
import com.lcjian.library.RetainViewFragment;
import com.lcjian.library.content.ConnectivityChangeHelper;
import com.lcjian.library.util.NetUtils;
import com.lcjian.library.util.SingleToast;
import com.lcjian.library.util.cache.DiskLruCache;
import com.lcjian.library.util.common.StorageUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.debug.E;
import com.viewpagerindicator.TabPageIndicator;
 
import org.apache.http.Header;
import org.json.JSONObject;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by weikou2015 on 2017/12/7.
 * 主页---精选
 */
 
public class RecommendTopFragment extends RetainViewFragment implements View.OnClickListener {
 
    private TextView tv_search_content, tv_category_top, tv_scan;
    private LinearLayout ll_no_net, ll_recommend_content, ll_no_data, ll_request_failture;
    private ConnectivityChangeHelper mChangeHelper;
//    private FrameLayout fl_indicator;
 
    private int REQUEST_CODE_SCAN = 111;
 
    /*
     * viewpager定义
     */
    GoogleMusicAdapter adapter;
    ViewPager pager;
    TabPageIndicator indicator;
    ProgressDialog pd = null;
 
    private View v_status_bar;
    private DiskLruCache cache;
    private boolean isCache = false;
 
    @Override
    public int getContentResource() {
        return R.layout.fragment_recommend_top;
    }
 
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            cache = DiskLruCache.open(
                    new File(StorageUtils.getCacheDirectory(getContext())
                            .toString(), "http"), getVersionNum(getContext()),
                    1, 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void onCreateView(View contentView, Bundle savedInstanceState) {
        v_status_bar = contentView.findViewById(R.id.v_status_bar);
                /*
         * 计算状态栏高度并设置
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int result = 0;
            int resourceId = getResources().getIdentifier("status_bar_height",
                    "dimen", "android");
            if (resourceId > 0) {
                result = getResources().getDimensionPixelSize(resourceId);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    result);
            v_status_bar.setLayoutParams(params);
        } else {
            v_status_bar.setVisibility(View.GONE);
        }
        tv_search_content = (TextView) contentView.findViewById(R.id.tv_search_content);
        tv_search_content.setOnClickListener(this);
        tv_scan = (TextView) contentView.findViewById(R.id.tv_scan);
        tv_scan.setOnClickListener(this);
        tv_category_top = (TextView) contentView.findViewById(R.id.tv_category_top);
        tv_category_top.setOnClickListener(this);
        ll_recommend_content = (LinearLayout) contentView.findViewById(R.id.ll_recommend_content);
        indicator = (TabPageIndicator) contentView.findViewById(R.id.indicator);
        pager = (ViewPager) contentView.findViewById(R.id.viewpager);
 
        ll_no_net = (LinearLayout) contentView.findViewById(R.id.ll_no_net);
        ll_no_data = (LinearLayout) contentView.findViewById(R.id.ll_no_data);
        ll_request_failture = (LinearLayout) contentView.findViewById(R.id.ll_request_failture);
        contentView.findViewById(R.id.iv_net_setting).setOnClickListener(this);
        contentView.findViewById(R.id.tv_refresh).setOnClickListener(this);
        mChangeHelper = new ConnectivityChangeHelper(ll_recommend_content.getContext(),
                new ConnectivityChangeHelper.OnConnectivityChangeListener() {
 
                    @Override
                    public void onNetworkUnAvailable() {
                    }
 
                    @Override
                    public void onNetworkAvailable() {
                        requestState(0);
                        if (mList.size() == 0 || isCache) {
                            setFirstCategory();
                        }
                    }
                });
//        setHotData();
        if (cache != null) {
            DiskLruCache.Snapshot snapshot = null;
            try {
                snapshot = cache.get(getKey("getFirstCategory"));
                if (snapshot != null) {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    List<FirstCategory> list = gson.fromJson(
                            snapshot.getString(0),
                            new TypeToken<List<FirstCategory>>() {
                            }.getType());
                    FirstCategory category = new FirstCategory();
                    category.setName("推荐");
                    mList.add(category);
                    mList.addAll(list);
                    adapter = new GoogleMusicAdapter(
                            getChildFragmentManager());
                    pager.setAdapter(adapter);
                    pager.setOffscreenPageLimit(0);
                    pager.setCurrentItem(0);
                    indicator.setViewPager(pager, 0);
 
                    isCache = true;
                    requestState(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (snapshot != null) {
                    snapshot.close();
                }
            }
        }
        setFirstCategory();
        ll_no_data.setOnClickListener(this);
    }
 
    private int getVersionNum(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 1;
        }
    }
 
    private String getKey(String method) {
        return new Md5FileNameGenerator().generate(method);
    }
 
 
    @Override
    public void onResume() {
        super.onResume();
        //设置状态栏文字颜色及图标为深色
        getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        MobclickAgent.onPageStart("精选");
        mChangeHelper.registerReceiver();
        ll_no_data.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mList.size() == 0) {
                    setFirstCategory();
                }
            }
        }, 2000);
    }
 
    @Override
    public void onPause() {
        super.onPause();
        mChangeHelper.unregisterReceiver();
        MobclickAgent.onPageEnd("精选");
    }
 
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search_content:
                Intent intent = new Intent(getContext(), SearchActivity.class);
                try {
                    intent.putExtra("content", tv_search_content.getHint().toString());
                } catch (Exception e) {
                }
                startActivity(intent);
                break;
            case R.id.tv_category_top:
                startActivity(new Intent(getContext(), CategoryTypeActivity.class));
                break;
            case R.id.ll_no_data:
                setFirstCategory();
                break;
            case R.id.tv_scan:
                Intent intent1 = new Intent(getContext(), CaptureActivity.class);
                /*ZxingConfig是配置类  可以设置是否显示底部布局,闪光灯,相册,是否播放提示音  震动等动能
                 * 也可以不传这个参数
                 * 不传的话  默认都为默认不震动  其他都为true
                 * */
                ZxingConfig config = new ZxingConfig();
                config.setPlayBeep(true);
                config.setShake(true);
                intent1.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                startActivityForResult(intent1, REQUEST_CODE_SCAN);
                break;
            case R.id.iv_net_setting:
                tv_category_top.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
                break;
            case R.id.tv_refresh:
                tv_category_top.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
//                requestState(0);
//                setFirstCategory();
                break;
        }
    }
 
 
    List<FirstCategory> mList = new ArrayList<>();
 
    private void setFirstCategory() {
        if (pd == null) {
            pd = new ProgressDialog(getContext());
            pd.setMessage("加载中...");
        }
        pd.show();
        ShoppingApi.getFirstCategory(getContext(), new BasicTextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }
 
            @Override
            public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
                if (jsonObject.optString("code").equalsIgnoreCase("0")) {
                    isCache = false;
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    List<FirstCategory> list = gson.fromJson(
                            jsonObject.optJSONObject("data")
                                    .optJSONArray("goodsClassList").toString(),
                            new TypeToken<List<FirstCategory>>() {
                            }.getType());
 
                    if (mList.size() > 0)
                        mList.clear();
 
                    FirstCategory category = new FirstCategory();
                    category.setName("推荐");
                    mList.add(category);
                    mList.addAll(list);
 
                    DiskLruCache.Editor editor = cache
                            .edit(getKey("getFirstCategory"));
                    editor.set(0, jsonObject.optJSONObject("data")
                            .optJSONArray("goodsClassList").toString());
                    editor.commit();
                    if (adapter == null) {
                        adapter = new GoogleMusicAdapter(
                                getChildFragmentManager());
                        pager.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
 
                    pager.setOffscreenPageLimit(0);
                    pager.setCurrentItem(0);
 
                    indicator.setViewPager(pager, 0);
                    indicator.setCurrentItem(0);
                    requestState(mList.size() == 0 ? 1 : 0);
//                            fl_indicator.addView(indicator);
                } else {
                    requestState(2);
                    SingleToast.showToast(getContext(), jsonObject.optString("msg"));
                }
            }
 
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable
                    throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                if (cache != null) {
                    DiskLruCache.Snapshot snapshot = null;
                    try {
                        snapshot = cache.get(getKey("getFirstCategory"));
                    } catch (Exception e) {
 
                    }
                    if (snapshot == null && mList.size() == 0) {
                        if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
                            requestState(3);
                            SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
                        } else {
                            requestState(2);
                            SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
                        }
                    } else {
                        if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
                            SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
                        } else {
                            SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
                        }
                    }
                } else {
                    if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
                        requestState(3);
                        SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
                    } else {
                        requestState(2);
                        SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
                    }
                }
            }
 
            @Override
            public void onFinish() {
                super.onFinish();
                if (pd.isShowing())
                    pd.dismiss();
            }
        });
    }
 
    class GoogleMusicAdapter extends FragmentPagerAdapter {
 
        public GoogleMusicAdapter(FragmentManager fm) {
            super(fm);
        }
 
        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return RecommendFragment.newInstance(mList.get(position));
            } else {
                return RecommendCategoryFragment.newInstance(mList.get(position));
            }
        }
 
        @Override
        public CharSequence getPageTitle(int position) {
            return mList.get(position % mList.size()).getName();
        }
 
        @Override
        public int getCount() {
            return mList.size();
        }
 
    }
 
 
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                if (content.contains("taobao://")) {
//                    Intent intent = new Intent(getContext(), GoodsDetailBrowerActivity.class);
                    Intent intent = new Intent(getContext(), GoodsBrowserActivity.class);
                    String id = content.substring(content.indexOf("//") + 2);
                    intent.putExtra("id", id);
                    startActivity(intent);
                } else {
                    SingleToast.showToast(getContext(), "非海草街商品!");
                }
            }
        }
    }
 
    /**
     * 请求状态 0 数据正常展示;1 返回数据为空;2 网络请求失败;3 没有连接网络
     *
     * @param state
     */
    private void requestState(int state) {
        ll_recommend_content.setVisibility(state == 0 ? View.VISIBLE : View.GONE);
        ll_no_data.setVisibility(state == 1 ? View.VISIBLE : View.GONE);
        ll_request_failture.setVisibility(state == 2 ? View.VISIBLE : View.GONE);
        ll_no_net.setVisibility(state == 3 ? View.VISIBLE : View.GONE);
    }
}