package com.yidianling.dynamic.trendsHome.content;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
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.widget.ImageView;
import android.widget.TextView;

import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydl_router.manager.YDLRouterManager;
import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.ydl.ydlcommon.view.WrapContentLinearLayoutManager;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
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.trendList.ITrendsListView;
import com.yidianling.dynamic.trendList.TrendsListPresenter;
import com.yidianling.dynamic.trendsDetail.TrendsDetailActivity;
import com.yidianling.dynamic.trendsHome.TrendsHomeFragment;

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

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

;

/**
 * @author Jim
 * @描述:
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/3 0003
 */
public class TrendsContentListFragment extends BaseFragment implements ITrendsListView {

    private RecyclerView trendsRcv;
    private NestedScrollView noDataRel;

    private final int REQUEST_CODE = 1001;
    public static final String KEY_TAB = "tab";
    public static final String KEY_TOPIC_ID = "topic_id";
    public static final String KEY_TREND_TYPE = "trend_type";
    public static final String KEY_USER_ID = "trend_user_id";
    public static final String TREND_TYPE_DEFAULT = "default";   //动态列表
    private final int eachPageDataNum = 7;

    private int tab;
    private int page;
    private int topic_id;
    private int last_id;
    private String trendType;
    private boolean isTrendsListLoading;
    private boolean isRefresh;
    private boolean isDoLikeAction;
    private TrendsListPresenter mPresenter;
    private TrendsCotentListAdapter mRcvAdapter;
    private List<TrendsListBean.Trend> trendsDatas;
    private RecyclerView.OnScrollListener mScrollListener;
    private int lastVisibleItem = 0;

    public static TrendsContentListFragment newInstance(int tabType, int topicId, String trendType, String trendUserid) {
        TrendsContentListFragment fragment = new TrendsContentListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_TAB, tabType);
        bundle.putInt(KEY_TOPIC_ID, topicId);
        bundle.putString(KEY_TREND_TYPE, trendType);
        bundle.putString(KEY_USER_ID, trendUserid);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int layoutResId() {
        return R.layout.dynamic_fragment_trend_list_in;
    }

    @Override
    public void initDataAndEvent() {
        initDatas();
        initViews();
        onRefresh();
    }

    @Override
    public void initDataAndEventLazy() {

    }

    private void initViews() {
        trendsRcv = getRootView().findViewById(R.id.recommend_dynamic_rcv);
        noDataRel = getRootView().findViewById(R.id.trend_no_data_rel);

        initRecyclerView();
    }

    private void initDatas() {
        isRefresh = false;
        isDoLikeAction = false;
        isTrendsListLoading = false;
        mPresenter = new TrendsListPresenter(this);
        tab = getArguments().getInt(KEY_TAB);
        topic_id = getArguments().getInt(KEY_TOPIC_ID);
        trendType = TextUtils.isEmpty(trendType = getArguments().getString(KEY_TREND_TYPE)) ? TREND_TYPE_DEFAULT : trendType;
        page = 1;
        last_id = 0;
    }

    private void initRecyclerView() {

        trendsDatas = new ArrayList<>();
        mRcvAdapter = new TrendsCotentListAdapter(getActivity(), trendsDatas);
        mRcvAdapter.setOnItemClickListener(new TrendsCotentListAdapter.OnItemClickListener() {
            @Override
            public void onItemLikeClick(View view, int position, List<TrendsListBean.Trend> mDatas) {
                doLikeAction(view, position, mDatas);
            }

            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(int id, int commentCount, int position) {
                TrendsListBean.Trend trend = trendsDatas.get(position - mRcvAdapter.getHeadersCount());
                //路由
                if (YDLRouterManager.Companion.router(trend.url)) {
                    return;
                }
                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)
                        .burryPoint("Dynamic_click");
                TrendsDetailActivity.startForResult(TrendsContentListFragment.this, id, commentCount, false, position, REQUEST_CODE);
            }

            @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(TrendsContentListFragment.this, id, commentCount, true, position, REQUEST_CODE);
            }
        });
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(getActivity(), WrapContentLinearLayoutManager.VERTICAL, false);
        trendsRcv.setAdapter(mRcvAdapter);
        trendsRcv.setLayoutManager(layoutManager);
        trendsRcv.getItemAnimator().setChangeDuration(0);  //解决局部刷新闪屏
        mRcvAdapter.addFooterView(getFooterView());
//        mScrollListener = new DynamicRecyclerViewScrollListener(layoutManager) {
//            @Override
//            public void onLoadMore(int page, int totalItemsCount, @org.jetbrains.annotations.Nullable RecyclerView view) {
//                LogUtil.e("tab=" + tab + ",onLoadMore");
//                LogUtil.e("tab=" + tab + ",==数据长度:" + mRcvAdapter.getDatas().size());
//                if (!isRefresh) {
//                    resetState();
//                    last_id = getLastId();
//                    LogUtil.i("loadMore last id: " + last_id + " page: " + page);
//                    TrendsContentListFragment.this.page++;
//                    switchDataToFetch();
//                }
//            }
//
//            @Override
//            protected void onScrollDown() {
//                LogUtil.e("tab=" + tab + ",onScrollDown");
////                ((TrendsHomeFragment) getParentFragment()).onScrollDown();
//            }
//
//            @Override
//            protected void onScrollUp() {
//                LogUtil.e("tab=" + tab + ",onScrollUp");
////                ((TrendsHomeFragment) getParentFragment()).onScrollUp();
//            }
//
//            @Override
//            public void onScrollTop() {
//                LogUtil.e("tab=" + tab + ",onScrollTop");
////                ((TrendsHomeFragment) getParentFragment()).onScrollTop();
//            }
//        };

        mScrollListener = new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LogUtil.e("tab===停止滑动" + System.currentTimeMillis());
                }

                if (newState == RecyclerView.SCROLL_STATE_IDLE //停止滚动
                        && lastVisibleItem >= (mRcvAdapter.getItemCount() - mRcvAdapter.getFootersCount())//最后一个显示的item序号大于适配器item数量，即显示了footer
                        && mRcvAdapter.getFooterState() == TrendsCotentListAdapter.FOOTRE_STATE_LOAD_MORE
                ) {
                    LogUtil.e("tab=" + tab + ",onLoadMore");
                    LogUtil.e("tab=" + tab + ",==数据长度:" + mRcvAdapter.getDatas().size());
                    if (!isRefresh) {
                        LogUtil.e("tab===加载数据" + System.currentTimeMillis());
                        last_id = getLastId();
                        LogUtil.i("loadMore last id: " + last_id + " page: " + page);
                        TrendsContentListFragment.this.page++;
                        switchDataToFetch();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        };
        trendsRcv.addOnScrollListener(mScrollListener);
    }

    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);
            }
        }
    }

    private void localData() {
        if (mPresenter != null) {
            mPresenter.localData(tab);
        }
    }

    private void fetchTrendsList() {
        if (!isTrendsListLoading) {
            isTrendsListLoading = true;
            if (mPresenter != null) {
                mPresenter.fetchTrendsInfo(tab, page, topic_id, last_id);
            }
        }
    }


    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;
    }

    @Override
    public void onResume() {
        super.onResume();
        if ("success".equals(SharedPreferencesEditor.getString("trend_state"))) {
            onRefresh();
        }
    }

    private void showLoadSuccessView() {
        if (noDataRel.getVisibility() != View.GONE) {
            noDataRel.setVisibility(View.GONE);
        }
        if (trendsRcv.getVisibility() != View.VISIBLE) {
            trendsRcv.setVisibility(View.VISIBLE);
        }
    }

    private void showErrorView() {
        if (page == 1) {
            trendsRcv.setVisibility(View.GONE);
            noDataRel.setVisibility(View.VISIBLE);
        } else {
            trendsRcv.setVisibility(View.VISIBLE);
            noDataRel.setVisibility(View.GONE);
        }
    }


    public void onRefresh() {
        isRefresh = true;
        page = 1;
        last_id = 0;
        fetchRecommendTopicList();
        switchDataToFetch();
    }

    private void fetchRecommendTopicList() {
        if (null != mPresenter) {
            mPresenter.fetchTopicListInfo(2, 0);
        }
    }

    private void switchDataToFetch() {
        if (isNeedLogin() && !DynamicIn.INSTANCE.isLogin()) {
            showErrorView();
            return;
        }
        SharedPreferencesEditor.putString("trend_state", "");
        LogUtil.d("trendType " + trendType);
//        localData();
        fetchTrendsList();
    }

    private boolean isNeedLogin() {
        tab = getArguments().getInt("tab");
        if (tab == 3) {  //关注
            return true;
        }
        return false;
    }

    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;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.d("fragmentlist onDestroy() " + tab);
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.d("requestCode " + requestCode + " resultcode: " + resultCode);
        if (data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE && resultCode == TrendsDetailActivity.RESULT_CODE) {
            int position = data.getIntExtra("position", 0);
            int likestate = data.getIntExtra("like_state", 0);
            int commentCount = data.getIntExtra("comment_count", 0);
            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);
            }
        }
    }

    @Override
    public void showLoadingDialog(boolean isNeedShowLoading) {

    }

    @Override
    public void hideLoadingView() {
    }

    @Override
    public void hideRefreshProgress() {
        isRefresh = false;
    }

    @Override
    public void showBanner(List<TrendsListBean.Banner> banner) {
        //更新banner数据
        if (getParentFragment() instanceof TrendsHomeFragment) {
            ((TrendsHomeFragment) getParentFragment()).setBannerData(banner);
        }
    }

    @Override
    public void showTrendsListView(List<TrendsListBean.Trend> data) {
        isTrendsListLoading = false;
        if (data==null||data.size()==0){
            noDataRel.setVisibility(View.VISIBLE);
            trendsRcv.setVisibility(View.GONE);
            return;
        }
        showLoadSuccessView();
        if (page == 1) {
            if (null == trendsDatas) {
                trendsDatas = new ArrayList();
            } else {
                trendsDatas.clear();
            }
            if (null != data) {
                trendsDatas.addAll(data);
            }
            mRcvAdapter.setDatas(trendsDatas, mRcvAdapter.FOOTRE_STATE_LOAD_MORE);
            mRcvAdapter.notifyDataSetChanged();
            return;
        }
        LogUtil.i("get datas  " + data.toString());
        if (data.size() >= eachPageDataNum) {
            trendsDatas.addAll(data);
            mRcvAdapter.setDatas(trendsDatas, mRcvAdapter.FOOTRE_STATE_LOAD_MORE);
            LogUtil.d("showTrendsListView 2: " + System.currentTimeMillis());
            if (page == 1) {
                mRcvAdapter.notifyDataSetChanged();
                return;
            }
            mRcvAdapter.notifyItemRangeInserted(trendsDatas.size() + mRcvAdapter.getHeadersCount() - data.size(), data.size());
        } else {
            LogUtil.i("get datas no more data" + data);
            trendsDatas.addAll(data);
            if (trendsDatas == null || trendsDatas.size() <= 0) {
                trendsRcv.setVisibility(View.GONE);
                noDataRel.setVisibility(View.VISIBLE);
                return;
            }

            mRcvAdapter.setDatas(trendsDatas, mRcvAdapter.FOOTER_STATE_NO_DATA);
            if (page == 1) {
                mRcvAdapter.notifyDataSetChanged();
                return;
            }
            mRcvAdapter.notifyItemRangeInserted(trendsDatas.size() + mRcvAdapter.getHeadersCount() - data.size(), data.size());
        }

    }

    @Override
    public void showTrendsErrorView(Throwable e) {
        isTrendsListLoading = false;
        showErrorView();
    }

    //推荐话题列表信息
    @Override
    public void showRecommendTopicView(TopicListDataBean topicListDatas) {
        ((TrendsHomeFragment) getParentFragment()).showMindsGroup(topicListDatas);
    }

    @Override
    public void showRecommendTopicErrorView(Throwable e) {
        LogUtil.i("Recommend Topic Fetch Failed: " + e.toString());
    }

    //未赞
    @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_icon_warm_nor);
        ((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 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_icon_warm_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 onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void showTopTrendsView(List<TrendsListBean.ExtData> extDatas) {
        if (extDatas != null && extDatas.size() > 0) {
            ((TrendsHomeFragment) getParentFragment()).showTopTrend(extDatas);
        }else{
            ((TrendsHomeFragment) getParentFragment()).setGoneLooperTextView();
        }
    }

    @Override
    public void showToast(String msg) {
        ToastUtil.toastShort(msg);
    }

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


    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();
    }
}
