admin
2021-05-14 1b4b3fed2569ac21ad6feb0a3a2c051175e7c36e
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package com.tejia.lijin.app.ui.trends;
 
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
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.wpc.library.RetainViewFragment;
import com.wpc.library.content.ConnectivityChangeHelper;
import com.wpc.library.util.NetUtils;
import com.wpc.library.util.RefreshLayout;
import com.wpc.library.util.common.DimenUtils;
import com.wpc.library.util.common.StringUtils;
import com.tejia.lijin.app.BasicTextHttpResponseHandler;
import com.tejia.lijin.app.R;
import com.tejia.lijin.app.ShoppingApi;
import com.tejia.lijin.app.entity.TrendsCategory;
import com.tejia.lijin.app.entity.TrendsInfo;
import com.tejia.lijin.app.ui.dialog.ShapeLoadingDialog;
import com.tejia.lijin.app.ui.invite.ShareBrowserActivity;
import com.tejia.lijin.app.util.clipboard.ClipboardUtil;
import com.tejia.lijin.app.util.user.LoginAndInviteStatusUtil;
import com.tejia.lijin.app.util.user.UserUtil;
 
import org.apache.http.Header;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * 动态--活动
 */
 
public class Trends2Fragmet extends RetainViewFragment {
    private RefreshLayout srl_trends;
    private RecyclerView rv_trends;
    private List<TrendsInfo> mList = new ArrayList<>();
    private int page = 1;
    private ImageView iv_slid_top;
    private View v_divider;
    private int count = 0;
    private Trends2Adapter adapter;
    private boolean isLoad = false;
    private View bottom;
    private TextView tv_loading;
    private ImageView iv_loading;
    private ConnectivityChangeHelper mChangeHelper;
    private LinearLayout ll_no_net, ll_no_data, ll_request_failture;
    private boolean haveCache = false;
    private String TYPE = "activity";
    private TextView tv_notice_content, tv_no_data_hint;
    private LinearLayout ll_notice;
    private ImageView iv_close, iv_no_data;
    private TrendsCategory mCategory;
    private int cId;
    private String cate;
 
    public static Trends2Fragmet newInstance(int cId, String cate, TrendsCategory category) {
        Trends2Fragmet fragment = new Trends2Fragmet();
        Bundle bundle = new Bundle();
        bundle.putSerializable("category", category);
        bundle.putInt("cid", cId);
        bundle.putString("cate", cate);
        fragment.setArguments(bundle);
        return fragment;
    }
 
    @Override
    public int getContentResource() {
        return R.layout.fragment_trends;
    }
 
    private ShapeLoadingDialog pd;
 
    @Override
    public void onCreateView(View contentView, Bundle savedInstanceState) {
        ll_no_net = contentView.findViewById(R.id.ll_no_net);
        ll_no_data = contentView.findViewById(R.id.ll_no_data);
        ll_request_failture = contentView.findViewById(R.id.ll_request_failture);
        v_divider = contentView.findViewById(R.id.v_divider);
 
        srl_trends = contentView.findViewById(R.id.srl_trends);
        rv_trends = contentView.findViewById(R.id.lv_trends);
 
        tv_notice_content = contentView.findViewById(R.id.tv_notice_content);
        ll_notice = contentView.findViewById(R.id.ll_notice);
        iv_close = contentView.findViewById(R.id.iv_close);
        tv_no_data_hint = contentView.findViewById(R.id.tv_no_data_hint);
        iv_no_data = contentView.findViewById(R.id.iv_no_data);
        tv_no_data_hint.setText("哎呀,最近没有什么活动哦~");
        iv_no_data.setImageDrawable(null);
        iv_no_data.setBackground(getActivity().getResources().getDrawable(R.drawable.iv_no_doings));
        /**小黄条*/
//        getAppPageNotification();
 
        pd = new ShapeLoadingDialog.Builder(getContext()).build();
 
        iv_slid_top = contentView.findViewById(R.id.iv_slid_top);
        float hRatio = 260 / 720f;
        float wRatio = 23 / 720f;
        int bottomPo = (int) (DimenUtils.getScreenWidth(getActivity()) * hRatio);
        int rightPo = (int) (DimenUtils.getScreenWidth(getActivity()) * wRatio);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(DimenUtils.dip2px(getActivity(), 40), DimenUtils.dip2px(getActivity(), 40));
        params.setMargins(0, 0, rightPo, bottomPo);
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        iv_slid_top.setLayoutParams(params);
        iv_slid_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv_trends.getLayoutManager().scrollToPosition(0);
                iv_slid_top.setVisibility(View.GONE);
            }
        });
        rv_trends.setLayoutManager(new LinearLayoutManager(srl_trends.getContext()));
//        DividerItemDecoration decoration = new DividerItemDecoration();
//        decoration.setSize(DimenUtils.dip2px(rv_trends.getContext(), 5));
//        rv_trends.addItemDecoration(decoration);
 
        mCategory = (TrendsCategory) getArguments().getSerializable("category");
        cId = getArguments().getInt("cid", 0);
        cate = getArguments().getString("cate");
        adapter = new Trends2Adapter(getActivity(), cate, mList, new SendCircleAdapter.CommentClickListener() {
            @Override
            public void onTagClick(int position) {
 
            }
 
            @Override
            public void onCopyClick(int position) {
                if (LoginAndInviteStatusUtil.acessNext(getContext(), UserUtil.getUid(getContext()), true)) {
                    //复制
                    ShoppingApi.copySpecialComment(getContext(), UserUtil.getUid(getContext()), mList.get(position).getId(), new BasicTextHttpResponseHandler() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            if (pd != null && !pd.isShowing())
                                pd.show();
                        }
 
                        @Override
                        public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
                            super.onSuccessPerfect(statusCode, headers, jsonObject);
                            if (jsonObject.optInt("code") == 0) {
                                String text = jsonObject.optJSONObject("data").optString("text");
                                ClipboardUtil.copy(getContext(), text);
                                Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getContext(), jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
                            }
                        }
 
                        @Override
                        public void onFailure(int statusCode, Header[] headers, String jsonObject, Throwable e) {
                            super.onFailure(statusCode, headers, jsonObject, e);
                        }
 
                        @Override
                        public void onFinish() {
                            super.onFinish();
                            if (pd != null && pd.isShowing())
                                pd.dismiss();
                        }
                    });
                }
            }
        });
        rv_trends.setAdapter(adapter);
 
        v_divider = contentView.findViewById(R.id.v_divider);
        v_divider.setVisibility(StringUtils.isEmpty(cate) ? View.GONE : View.VISIBLE);
        bottom = LayoutInflater.from(srl_trends.getContext()).inflate(R.layout.item_recyclerview_bottom, null);
        adapter.addFooterView(bottom);
        bottom.setVisibility(View.GONE);
        tv_loading = bottom.findViewById(R.id.tv_loading);
        iv_loading = bottom.findViewById(R.id.iv_loading);
        AnimationDrawable animationDrawable = (AnimationDrawable) getResources().getDrawable(
                R.drawable.anim_list_loading);
        iv_loading.setImageDrawable(animationDrawable);
        animationDrawable.start();
//        Glide.with(this).load(R.drawable.gif_loading).into(iv_loading);
        bottom.setVisibility(View.GONE);
        srl_trends.setColorSchemeColors(getResources().getColor(R.color.theme));
        contentView.findViewById(R.id.tv_net_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                srl_trends.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
            }
        });
        contentView.findViewById(R.id.tv_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rv_trends.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
            }
        });
        mChangeHelper = new ConnectivityChangeHelper(srl_trends.getContext(),
                new ConnectivityChangeHelper.OnConnectivityChangeListener() {
 
                    @Override
                    public void onNetworkUnAvailable() {
                        if (mList.size() == 0)
                            requestState(3);
                    }
 
                    @Override
                    public void onNetworkAvailable() {
                        if (mList.size() == 0 || haveCache) {
                            getTrendsList();
                        }
                    }
                });
        rv_trends.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int first = manager.findFirstVisibleItemPosition();
                int last = manager.findLastVisibleItemPosition();
                int total = manager.getItemCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (first == 0) {
                        iv_slid_top.setVisibility(View.GONE);
                    }
                    if (last == total - 1 && mList.size() < count && isLoad) {
                        page++;
                        isLoad = false;
                        iv_loading.setVisibility(View.VISIBLE);
                        tv_loading.setText("正在加载更多数据");
                        getTrendsList();
                    }
                }
//                else {
//                    iv_slid_top.setVisibility(View.GONE);
//                }
            }
 
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, final int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (Math.abs(dy) > 10) {
                    if (dy > 0) {
                        iv_slid_top.setVisibility(View.GONE);
                    } else {
                        iv_slid_top.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        srl_trends.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getTrendsList();
            }
        });
        rv_trends.setAdapter(adapter);
        srl_trends.setRefreshing(true);
//        handler_timeCurrent.sendEmptyMessage(1001);
    }
 
    private boolean isCancel = false;//来标识是fragment否退出
    //这里很重要,使用Handler的延时效果,每隔一秒刷新一下适配器,以此产生倒计时效果
    @SuppressLint("HandlerLeak")
    private Handler handler_timeCurrent = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //isCancel,防止界面销毁时,再一次改变UI
            if (isCancel || handler_timeCurrent == null) {
                return;
            }
            setCountdown();//计算倒计时
            if (msg.what == 1001) {
                handler_timeCurrent.sendEmptyMessageDelayed(1001, 1000);
            }
        }
    };
 
    /**
     * 计算倒计时
     */
    private void setCountdown() {
        if (mList.size() > 0) {
            for (int i = 0; i < mList.size(); i++) {
                TrendsInfo tr = mList.get(i);
                long time = tr.getCountDownTime();
                if (time > 0) {
                    long days = time / (24 * 60 * 60);//这个时间相差的天数整数,大于1天为前天的时间了,小于24小时则为昨天和今天的时间
                    long hours = (time / (60 * 60) - days * 24);//这个时间相差的减去天数的小时数
                    long min = ((time / (60)) - days * 24 * 60 - hours * 60);//
//                    long s = (time - days * 24 * 60 * 60 - hours * 60 * 60 - min * 60);
                    mList.get(i).setDays(setTimeSupplement(days));
                    mList.get(i).setHours(setTimeSupplement(hours));
                    mList.get(i).setMin(setTimeSupplement(min));
                    mList.get(i).setCountDownTime((tr.getCountDownTime() - 1L));
                } else {
                    mList.get(i).setDays(setTimeSupplement(0));
                    mList.get(i).setHours(setTimeSupplement(0));
                    mList.get(i).setMin(setTimeSupplement(0));
                }
            }
            adapter.notifyDataSetChanged();
        }
    }
 
    /**
     * 时间添加0
     *
     * @param time
     * @return
     */
    private String setTimeSupplement(long time) {
        String t = "";
        if (time < 10 && time > 0) {
            t = "0" + time;
        } else if (time == 0 || time >= 10) {
            t = "" + time;
        }
        return t;
    }
 
    @Override
    public void onResume() {
        super.onResume();
        mChangeHelper.registerReceiver();
//        if (adapter != null)
//            adapter.onActivityResume();
    }
 
    @Override
    public void onPause() {
        super.onPause();
        mChangeHelper.unregisterReceiver();
    }
 
    private void getAppPageNotification() {
        ShoppingApi.getAppPageNotification(rv_trends.getContext(), TYPE, new BasicTextHttpResponseHandler() {
            @Override
            public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
                if (jsonObject.optInt("code") == 0) {
                    boolean isClose = jsonObject.optJSONObject("data").optBoolean("canClose");
                    String content = jsonObject.optJSONObject("data").optString("content");
                    final String contentUrl = jsonObject.optJSONObject("data").optString("contentUrl");
                    final String md5 = jsonObject.optJSONObject("data").optString("md5");
 
                    tv_notice_content.setVisibility(!StringUtils.isEmpty(content) ? View.VISIBLE : View.GONE);
                    tv_notice_content.setText(content);
                    final SharedPreferences sp = rv_trends.getContext().getSharedPreferences("notice", Context.MODE_PRIVATE);
                    if (!sp.getBoolean(md5, false)) {//false 展示,true不展示
                        ll_notice.setVisibility(View.VISIBLE);
                    } else {
                        ll_notice.setVisibility(View.GONE);
                    }
 
                    if (isClose) {
                        iv_close.setImageDrawable(getResources().getDrawable(R.drawable.ic_notice_close));
                        iv_close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ll_notice.setVisibility(View.GONE);
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putBoolean(md5, true);
                                editor.commit();
                            }
                        });
                    } else {
                        iv_close.setImageDrawable(getResources().getDrawable(R.drawable.ic_notice_input));
                    }
                    ll_notice.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (StringUtils.isEmpty(contentUrl))
                                return;
                            Intent intent = new Intent(rv_trends.getContext(), ShareBrowserActivity.class);
                            intent.putExtra("url", contentUrl);
                            rv_trends.getContext().startActivity(intent);
                        }
                    });
                } else {
                    ll_notice.setVisibility(View.GONE);
                }
            }
 
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }
 
    /**
     * 动态 活动请求
     */
    private void getTrendsList() {
        System.out.println("getTrendsList" + page);
        ShoppingApi.getRecommendActivity(srl_trends.getContext(), page + "", cId + "",
                mCategory != null ? mCategory.getId() + "" : "", new BasicTextHttpResponseHandler() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        if (page > 0) {
                            bottom.setVisibility(View.VISIBLE);
                        } else {
                            bottom.setVisibility(View.GONE);
                        }
                    }
 
                    @Override
                    public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
                        ll_request_failture.setVisibility(View.GONE);
                        bottom.setVisibility(View.GONE);
                        if (jsonObject.optString("code").equalsIgnoreCase("0")) {
                            haveCache = false;
                            Gson gson = new GsonBuilder().serializeNulls().create();
                            List<TrendsInfo> list = gson.fromJson(
                                    jsonObject.optJSONObject("data").optJSONArray("list").toString(),
                                    new TypeToken<List<TrendsInfo>>() {
                                    }.getType());
                            if (page == 1)
                                mList.clear();
                            mList.addAll(list);
                            adapter.notifyDataSetChanged();
                            setCountdown();//计算倒计时
//                    adapter.notifyItemRangeChanged(mList.size(), mList.size() - list.size() + 1);//倒序批量刷新列表
                            count = Integer.parseInt(jsonObject.optJSONObject("data").optString("count"));
                            if (mList.size() == count) {
                                bottom.setVisibility(View.VISIBLE);
                                iv_loading.setVisibility(View.GONE);
                                tv_loading.setText(getResources().getString(R.string.list_no_more));
                            }
 
 
                            requestState(mList.size() == 0 ? 1 : 0);
                        } else {
                            if (mList.size() == 0)
                                requestState(2);
                        }
                    }
 
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        srl_trends.setRefreshing(false);
                        isLoad = true;
                    }
 
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        bottom.setVisibility(View.GONE);
                        if (NetUtils.getNetworkState(srl_trends.getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
                            requestState(3);
                            Toast.makeText(srl_trends.getContext(), "网络未连接,请检测网络设置", Toast.LENGTH_SHORT).show();
                        } else {
                            requestState(2);
                            Toast.makeText(srl_trends.getContext(), "网络连接异常,请检测网络设置", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
 
    /**
     * 请求状态 0 数据正常展示;1 返回数据为空;2 网络请求失败;3 没有连接网络
     *
     * @param state
     */
    private void requestState(int state) {
        srl_trends.setVisibility(state == 0 ? View.VISIBLE : View.GONE);
        rv_trends.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);
    }
 
    //防止当前Activity结束以后,   handler依然继续循环浪费资源
    @Override
    public void onDestroy() {
        isCancel = true;
        handler_timeCurrent.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}