package com.yidianling.dynamic.trendList;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.DynamicFragment;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.members.MembersActivity;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.model.TopicListDataBean;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.model.ZanResult;
import com.yidianling.dynamic.router.DynamicIn;
import com.yidianling.dynamic.topic.topicDetail.TopicDetailActivity;
import com.yidianling.dynamic.trendList.adapter.TrendsListAdapter;
import com.yidianling.dynamic.trendsDetail.TrendsDetailActivity;
import com.yidianling.dynamic.trendsHome.TrendsHomeFragment;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.view.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 话题详情动态或者用户个人主页动态俩表界面
 * Created by xiongyu on 2017/3/13.
 * Refactor by Jim on 2018/1/2 0002  .
 * 2018/1/2 0002 将首页动态列表以及这个该列表类的公共部分提取
 */
public class TrendListInFragment extends DynamicFragment implements ITrendsListView {

    Context context;
    private RecyclerView trendsRcv;
    private ImageView mTrendNoDataIv;
    private TextView mTrendNoDataTv;
    private NestedScrollView mTrendNoDataRel;

    int totalItemCount, lastVisibleItem, visibleItemCount, firstVisibleItem;
    private List<TrendsListBean.Trend> trendsDatas;
    private TrendsListAdapter mRcvAdapter;
    private RecyclerView.OnScrollListener mScrollListener;
    private TrendsListPresenter mPresenter;
    private boolean isTrendsListLoading;
    private boolean isDoLikeAction;
    private int last_id;
    private int page = 1;
    private String trendType;
    private String topicId = "0";
    private String userId;
    //加载更多
    private String tab = "1";

    public static TrendListInFragment newInstance(String tab1, String topic_id, String GetTrendType, String Trend_User_id) {
        TrendListInFragment newsFragment = new TrendListInFragment();
        Bundle args = new Bundle();
        args.putString("tab", tab1);
        args.putString("topic_id", topic_id);
        args.putString("GetTrendType", GetTrendType);
        args.putString("Trend_User_id", Trend_User_id);
        newsFragment.setArguments(args);
        return newsFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        tab = getArguments().getString("tab");
        LogUtil.d("onAttach tab: " + tab);
        if (context instanceof TopicDetailActivity) {
            topicDetailActivity = (TopicDetailActivity) context;
            topicDetailActivity.setHandler(mHandler, tab);
        } else if (context instanceof MembersActivity) {
            membersActivity = (MembersActivity) context;
            membersActivity.setHandler(mHandler, tab);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dynamic_fragment_trend_list_in, container, false);
        bindView(view);
        initFileds();
        initView();
        fetchDatas();
        return view;
    }

    private void initFileds() {
        LogUtil.d("initFileds");
        isTrendsListLoading = false;
        isDoLikeAction = false;
        mPresenter = new TrendsListPresenter(this);
        context = getActivity().getApplicationContext();
//        tab = getArguments().getString("tab");
        topicId = getArguments().getString("topic_id");
        trendType = getArguments().getString("GetTrendType");
        userId = getArguments().getString("Trend_User_id");
        last_id = 0;
    }

    private void initView() {
        if ("default".equals(trendType)) {
            mTrendNoDataTv.setText("今天等你来发布咯～");
        } else {
            mTrendNoDataTv.setText("TA有点懒，点亮红心赐给他点能量");
        }
        trendsDatas = new ArrayList<>();
        mRcvAdapter = new TrendsListAdapter(getActivity(), trendsDatas);
        mRcvAdapter.setOnItemClickListener(new TrendsListAdapter.OnItemClickListener() {
            @Override
            public void onItemLikeClick(View view, int position, List<TrendsListBean.Trend> mDatas) {
                doLikeAction(view, position, mDatas);
            }

            @Override
            public void onItemClick(int id, int commentCount, int position) {
                if (mRcvAdapter.getHeadersCount() <= position && trendsDatas.size() != 0) {
                    TrendsListBean.Trend trend = trendsDatas.get(position - mRcvAdapter.getHeadersCount());
                    if (trend.isAd == 1) {
                        //广告跳转H5
                        NewH5Activity.start(getContext(), new H5Params(trend.url, null, trend.share));
                        DynamicApiUtils.adClickCount(new Command.AdClickCount(trend.focId))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(objectBaseResponse -> {

                                }, throwable -> {

                                });
                        return;
                    }
                    BuryPointUtils.getInstance().createMap()
                            .put("dynamic_ID", trend.id)
                            .put("dynamic_name", trend.title)
                            .put("dynamic_type", trend.topicTitle == null ? "" : trend.topicTitle)
                            .burryPoint("Dynamic_click");
                    TrendsDetailActivity.startForResult(TrendListInFragment.this, id, commentCount, false, position, DynamicConstants.JUMP_TREND_INFO);
                }
            }

            @Override
            public void onItemCommentClick(int id, int commentCount, int position) {
                BuryPointUtils.getInstance().createMap()
                        .put("dynamic_name", trendsDatas.get(position - mRcvAdapter.getHeadersCount()).title)
                        .put("dynamic_ID", trendsDatas.get(position - mRcvAdapter.getHeadersCount()).id)
                        .put("dynamic_type", trendsDatas.get(position - mRcvAdapter.getHeadersCount()).topicTitle)
                        .burryPoint("Comment_dynamic");
                TrendsDetailActivity.startForResult(TrendListInFragment.this, id, commentCount, true, position, DynamicConstants.JUMP_TREND_INFO);
            }
        });
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(getActivity(), WrapContentLinearLayoutManager.VERTICAL, false);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        trendsRcv.setAdapter(mRcvAdapter);
        trendsRcv.setLayoutManager(layoutManager);
        trendsRcv.getItemAnimator().setChangeDuration(0);  //解决局部刷新闪屏
        mScrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (RecyclerView.SCROLL_STATE_IDLE == newState) {
                    if (!isTrendsListLoading && totalItemCount <= (lastVisibleItem + 1) && totalItemCount > visibleItemCount && visibleItemCount > 0) {
                        last_id = getLastId();
                        LogUtil.i("loadMore last id: " + last_id + " page: " + page);
                        TrendListInFragment.this.page++;
                        fetchDatas();
                    }
                    int pos = layoutManager.findFirstCompletelyVisibleItemPosition();
                    if (pos >= 10) {
                        Fragment parentFragment = getParentFragment();
                        if (parentFragment != null && parentFragment instanceof TrendsHomeFragment) {
                            ((TrendsHomeFragment) parentFragment).displayShowCase();
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    WrapContentLinearLayoutManager layoutManager = (WrapContentLinearLayoutManager) recyclerView.getLayoutManager();
                    totalItemCount = layoutManager.getItemCount();
                    firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                    lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                    visibleItemCount = layoutManager.getChildCount();

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

        };
        trendsRcv.addOnScrollListener(mScrollListener);
        mRcvAdapter.addFooterView(getFooterView());
    }

    private void fetchDatas() {
        //加载本地缓存
        localListData();
        LogUtil.d("trendType " + trendType);
        if ("default".equals(trendType)) {
            getTopicTrends();
        } else if ("member_trend".equals(trendType)) {
            getMemberTrends();
        }
    }

    /**
     * 加载本地缓存数据
     */
    private void localListData() {
        if (null != mPresenter) {
            mPresenter.localData(Integer.valueOf(tab));
        }
    }

    private void getTopicTrends() {
        SharedPreferencesEditor.putString("trend_state", "");
        if (!isTrendsListLoading) {
            isTrendsListLoading = true;
            mPresenter.fetchTrendsInfo(Integer.valueOf(tab), page, Integer.valueOf(topicId), last_id);
        }
    }

    private void getMemberTrends() {
        if (!isTrendsListLoading) {
            isTrendsListLoading = true;
            mPresenter.fetchUserTrendsList(userId, page, 1);
        }
    }

    private View getFooterView() {
        View view;
        if (trendsRcv != null) {
            view = LayoutInflater.from(getActivity()).inflate(R.layout.dynamic_progress_item, trendsRcv, false);
        } else {
            view = LayoutInflater.from(getActivity()).inflate(R.layout.dynamic_progress_item, null);
        }
        return view;
    }

    private int getLastId() {
        String id = "0";
        if (trendsDatas != null && trendsDatas.size() > 0) {
            LogUtil.i("TAG get last content: " + trendsDatas.get(trendsDatas.size() - 1).toString());
            id = trendsDatas.get(trendsDatas.size() - 1).id;
            if (id == null || id.equals("")) {
                return 0;
            } else {
                return Integer.valueOf(id);
            }
        }
        return 0;
    }

    private void doLikeAction(View view, int position, List<TrendsListBean.Trend> mDatas) {
        if (DynamicIn.INSTANCE.loginByOneKeyLogin(getActivity(),true)) {
            if (!isDoLikeAction) {
                isDoLikeAction = true;
                mPresenter.doLikeAction(view, position, Integer.valueOf(mDatas.get(position).id), mDatas);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if ("success".equals(SharedPreferencesEditor.getString("trend_state"))) {
            page = 1;
            trendsDatas.clear();
            fetchDatas();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null && resultCode != TrendsDetailActivity.RESULT_CODE) {
            return;
        }
        int position = data.getIntExtra("position", 0);
        int likestate = data.getIntExtra("like_state", 0);
        int commentCount = data.getIntExtra("comment_count", 0);
        switch (requestCode) {
            case DynamicConstants.JUMP_TREND_INFO:
                if (data.getStringArrayListExtra("comment_datas") != null) {
                    LogUtil.d("comment data is not null");
                    if (data.getStringArrayListExtra("comment_datas").size() > 0) {
                        List<TrendsListBean.Trend.Comments> comments = new ArrayList<>();
                        for (String commentStr : data.getStringArrayListExtra("comment_datas")) {
                            String[] str = commentStr.split("/");
                            TrendsListBean.Trend.Comments comment = new TrendsListBean.Trend.Comments();
                            LogUtil.d("str length: " + str.length);
                            comment.name = str[0];
                            comment.content = str[1];
                            comment.to_name = str.length == 3 ? !TextUtils.isEmpty(str[2]) ? str[2] : "" : "";
                            comments.add(comment);
                        }
                        mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).comments = comments;
                        mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).commentsCount = commentCount;
                        mRcvAdapter.notifyItemChanged(position);
                    } else {
                        mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).comments.clear();
                        mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).commentsCount = commentCount;
                        mRcvAdapter.notifyItemChanged(position);
                    }
                }
                LogUtil.d("resultcode: " + resultCode + " position: " + position + " likestate: " + likestate);
                if (likestate != 0) {
                    mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).zanCount = mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).zanCount + (mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).isZan - likestate);
                    mRcvAdapter.getDatas().get(position - mRcvAdapter.getHeadersCount()).isZan = likestate;
                    mRcvAdapter.notifyItemChanged(position);
                }
                break;
        }
    }


    private TopicDetailActivity topicDetailActivity;
    private MembersActivity membersActivity;

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            LogUtil.d("what: " + msg.what + " tab: " + tab);
            switch (msg.what) {
                case DynamicConstants.TOPIC_DETAIL_NEW_REFRESH:
                    if (!tab.equals("1")) {
                        break;
                    }
                    topicId = (String) msg.obj;
                    page = 1;
                    if (isTrendsListLoading == false) {
                        fetchDatas();
                    }
                    break;
                case DynamicConstants.TOPIC_DETAIL_HOT_REFRESH:
                    if (!tab.equals(2)) {
                        break;
                    }
                    topicId = (String) msg.obj;
                    page = 1;
                    if (isTrendsListLoading == false) {
                        fetchDatas();
                    }
                    break;
                case DynamicConstants.MEMBER_REFRESH:
                    trendType = "member_trend";
                    userId = (String) msg.obj;
                    topicId = "0";
                    page = 1;
                    if (isTrendsListLoading == false) {
                        fetchDatas();
                    }
                    break;
            }
        }

        ;
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void showLoadingDialog(boolean isNeedShowLoading) {
        if (trendType.equals("member_trend")) {
            showProgressDialog(getActivity().getString(R.string.dynamic_dialog_loading));
        }
    }

    @Override
    public void hideLoadingView() {
        dismissProgressDialog();
    }

    @Override
    public void hideRefreshProgress() {
    }

    @Override
    public void showBanner(List<TrendsListBean.Banner> banner) {

    }

    @Override
    public void showTrendsListView(List<TrendsListBean.Trend> data) {
        isTrendsListLoading = false;
        if (page == 1) {
            showLoadSuccessView();
            trendsDatas.clear();
            trendsDatas.addAll(data);
            mRcvAdapter.notifyDataSetChanged();
            return;
        }
        LogUtil.i("TAG get datas  " + data.toString());
        if (data.size() >= DynamicConstants.EACH_PAGE_DATA_NUM) {
            showLoadSuccessView();
            trendsDatas.addAll(data);
            mRcvAdapter.setDatas(trendsDatas, mRcvAdapter.FOOTRE_STATE_LOAD_MORE);
            mRcvAdapter.notifyDataSetChanged();
        } else {
            LogUtil.i("TAG get datas no more data" + data);
            trendsDatas.addAll(data);
            mRcvAdapter.setDatas(trendsDatas, mRcvAdapter.FOOTER_STATE_NO_DATA);
            mRcvAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showTrendsErrorView(Throwable e) {
        isTrendsListLoading = false;
        if (page == 1) {
            mTrendNoDataRel.setVisibility(View.VISIBLE);
            trendsRcv.setVisibility(View.GONE);
        } else {
            trendsRcv.setVisibility(View.VISIBLE);
            mTrendNoDataRel.setVisibility(View.GONE);
        }
    }

    @Override
    public void showRecommendTopicView(TopicListDataBean topicListDatas) {
    }

    @Override
    public void showRecommendTopicErrorView(Throwable e) {
    }

    @Override
    public void showLikedView(View view, int position, ZanResult zanResultBaseBean, List<TrendsListBean.Trend> mDatas) {
        BuryPointUtils.getInstance().createMap()
                .put("warmth_dynamic_name", mDatas.get(position).title)
                .put("warmth_dynamic_ID", mDatas.get(position).id)
                .put("warmth_category", mDatas.get(position).topicTitle)
                .put("warmth_way", "动态流页面")
                .burryPoint("Warmth_dynamic");
        mDatas.get(position).isZan = 1;
        mDatas.get(position).zanCount += 1;
        ((ImageView) view.findViewById(R.id.item_trend_zan_iv)).setImageResource(R.drawable.dynamic_newsfeed_like_sel);
        ((TextView) view.findViewById(R.id.text_zan_num)).setText(mDatas.get(position).zanCount + "");
        startLikeViewAnimation(view.findViewById(R.id.item_trend_zan_iv), position);
        isDoLikeAction = false;
    }

    @Override
    public void showDisLikeView(View view, int position, ZanResult zanResultBaseBean, List<TrendsListBean.Trend> mDatas) {
        mDatas.get(position).isZan = 2;
        mDatas.get(position).zanCount -= 1;
        ((ImageView) view.findViewById(R.id.item_trend_zan_iv)).setImageResource(R.drawable.dynamic_newsfeed_like);
        ((TextView) view.findViewById(R.id.text_zan_num)).setText(String.valueOf(mDatas.get(position).zanCount));
        startLikeViewAnimation(view.findViewById(R.id.item_trend_zan_iv), position);
        isDoLikeAction = false;
    }

    @Override
    public void showTopTrendsView(List<TrendsListBean.ExtData> extDatas) {
    }

    @Override
    public void showToast(String msg) {
    }

    @Override
    public void showLikeActionFailed() {
        isDoLikeAction = false;
    }


    private void showLoadSuccessView() {
        mTrendNoDataRel.setVisibility(View.GONE);
        trendsRcv.setVisibility(View.VISIBLE);
    }

    private void startLikeViewAnimation(View view, int position) {
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.5f, 1f);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.5f, 1f);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(500);
        set.playTogether(animator1, animator2);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
            }
        });
        set.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    private void bindView(View bindSource) {
        trendsRcv = bindSource.findViewById(R.id.recommend_dynamic_rcv);
        mTrendNoDataIv = bindSource.findViewById(R.id.trend_no_data_iv);
        mTrendNoDataTv = bindSource.findViewById(R.id.trend_no_data_tv);
        mTrendNoDataRel = bindSource.findViewById(R.id.trend_no_data_rel);
    }
}
