package com.yidianling.dynamic.trendsHome;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.ScreenUtil;
import com.yidianling.common.tools.RxDeviceTool;
import com.yidianling.common.tools.RxImageTool;
import com.yidianling.dynamic.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.R2;
import com.yidianling.dynamic.common.view.LooperTextView;
import com.yidianling.dynamic.model.TopicListDataBean;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.publishTrend.PublishTrendActivity;
import com.yidianling.dynamic.router.DynamicIn;
import com.yidianling.dynamic.topic.AllTopicActivity;
import com.yidianling.dynamic.topic.topicDetail.TopicDetailActivity;
import com.yidianling.dynamic.trendsHome.content.TrendsContentListFragment;
import com.yidianling.dynamic.trendsHome.view.TrendsHomeBannerView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * Created by Jim on 2017/9/22 0022.
 * 首页问答fragment
 */

public class TrendsHomeFragment extends BaseFragment implements ITrendHomeView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R2.id.trend_home_swl)
    SwipeRefreshLayout swl;

    @BindView(R2.id.vp_content)
    ViewPager vpContent;

    @BindView(R2.id.trends_topic_iv1)
    ImageView topicRoundIv1;

    @BindView(R2.id.trends_topic_iv2)
    ImageView topicRoundIv2;

    @BindView(R2.id.trends_topic_iv3)
    ImageView topicRoundIv3;

    @BindView(R2.id.trends_home_csl)
    ConstraintLayout mConstraintLayout;

    @BindView(R2.id.trends_tv_mind_group)
    TextView tvMindGroup;

    @BindView(R2.id.trends_tv_mind_more)
    TextView tvMindMore;

    @BindView(R2.id.frl_topic_iv3)
    FrameLayout frlTopicIv3;

    @BindView(R2.id.frl_topic_iv2)
    FrameLayout frlTopicIv2;

    @BindView(R2.id.frl_topic_iv1)
    FrameLayout frlTopicIv1;

    @BindView(R2.id.trends_home_appBar)
    AppBarLayout mAppBarLayout;
    @BindView(R2.id.item_recommend_tv)
    TextView mItemRecommendTv;
    @BindView(R2.id.item_hot_tv)
    TextView mItemHotTv;
    @BindView(R2.id.item_focus_tv)
    TextView mItemFocusTv;
    @BindView(R2.id.trends_topic_tv3)
    TextView trendsTopicTv3;
    @BindView(R2.id.trends_topic_tv2)
    TextView trendsTopicTv2;
    @BindView(R2.id.trends_topic_tv1)
    TextView trendsTopicTv1;
    @BindView(R2.id.publish_trend_btn)
    FloatingActionButton mPublishTrendButton;
    @BindView(R2.id.ternd_loop_tv)
    LooperTextView mLooperTextView;
    @BindView(R2.id.toolbar_tv)
    Toolbar mToolBarTv;
    @BindView(R2.id.v_banner)
    TrendsHomeBannerView v_banner;


    private Unbinder mUnbinder;
    private TrendsHomePresenter mPresenter;
    private Fragment[] mFragments;
    private TrendsHomeVpAdapter vpAdapter;
    private long lastTabClick = 0;
    String tab;

    public TrendsHomeFragment setTab(String tab) {
        this.tab = tab;
        return this;
    }

    public static TrendsHomeFragment newInstance() {
        return new TrendsHomeFragment();
    }


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

    @Override
    public void initDataAndEvent() {
        mUnbinder = ButterKnife.bind(this, getView());
        initViews();
        initDatas();

    }

    @Override
    public void initDataAndEventLazy() {
        initDatas();
    }

    private void initViews() {
        initBannerView();
        swl.setOnRefreshListener(this);
        swl.setColorSchemeResources(R.color.dynamic_main_theme);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    swl.setEnabled(true);
                } else {
                    swl.setEnabled(false);
                }
                if (verticalOffset <= -appBarLayout.getTotalScrollRange() + mToolBarTv.getHeight()) {
                    mToolBarTv.setAlpha(1f);
                } else {
                    mToolBarTv.setAlpha(0f);
                }
            }
        });
        initStatus();
    }

    private void initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
            int statusBarHeight = ScreenUtil.getStatusBarHeight(getActivity());
            CollapsingToolbarLayout.LayoutParams layoutParams = (CollapsingToolbarLayout.LayoutParams) mToolBarTv.getLayoutParams();
            layoutParams.height = (int) (getResources().getDimension(R.dimen.title_bar_height) + statusBarHeight);
            mToolBarTv.setPadding(0, statusBarHeight, 0, 0);
            mToolBarTv.setLayoutParams(layoutParams);

        }
    }

    private void initDatas() {
        mPresenter = new TrendsHomePresenter();
        mPresenter.callBack = this;
        mPresenter.fetchDats();
    }

    private void initBannerView() {
        int screenSize = RxDeviceTool.getScreenWidth(getActivity());
        int topicRoundIv1Width = (screenSize - RxImageTool.dip2px(31)) * 2 / 3;
        int topicRoundIv23Width = (screenSize - RxImageTool.dip2px(31)) / 3;

        int topicRoundIv1Height = (int) (topicRoundIv1Width / 1.5f);
        int topicRoundIv23Height = (int) ((topicRoundIv1Height - RxImageTool.dip2px(1)) / 2f);

        ConstraintLayout.LayoutParams params1 = new ConstraintLayout.LayoutParams(topicRoundIv1Width, topicRoundIv1Height);
        params1.topMargin = RxImageTool.dp2px(10);
        params1.leftMargin = RxImageTool.dp2px(15);
        params1.leftToRight = mConstraintLayout.getId();
        params1.topToBottom = tvMindGroup.getId();
        frlTopicIv1.setLayoutParams(params1);

        ConstraintLayout.LayoutParams params2 = new ConstraintLayout.LayoutParams(topicRoundIv23Width, topicRoundIv23Height);
        params2.topMargin = RxImageTool.dp2px(10);
        params2.leftMargin = RxImageTool.dp2px(1);
        params2.leftToRight = frlTopicIv1.getId();
        params2.topToBottom = tvMindGroup.getId();
        frlTopicIv2.setLayoutParams(params2);

        ConstraintLayout.LayoutParams params3 = new ConstraintLayout.LayoutParams(topicRoundIv23Width, topicRoundIv23Height);
        params3.topMargin = RxImageTool.dp2px(1);
        params3.leftMargin = RxImageTool.dp2px(1);
        params3.leftToRight = frlTopicIv1.getId();
        params3.topToBottom = frlTopicIv2.getId();
        frlTopicIv3.setLayoutParams(params3);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void initViewPager() {
        vpAdapter = new TrendsHomeVpAdapter(getChildFragmentManager(), mFragments);
        vpContent.setAdapter(vpAdapter);
        vpContent.setOffscreenPageLimit(1);
        vpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position >= 1) {
                    vpContent.setOffscreenPageLimit(2);
                }

                switchTab(position);
                switch (position) {
                    case 0:
                        BuryPointUtils.getInstance().createMap()
                                .put("toptab_name", "推荐")
                                .burryPoint("topTabClick");
                        BuryPointUtils.getInstance().trackViewScreen(getActivity(), "动态-推荐", "com.cxzapp.yidianling.trends.trendList.TrendsListFragment");
                        break;
                    case 1:
                        BuryPointUtils.getInstance().createMap()
                                .put("toptab_name", "最新")
                                .burryPoint("topTabClick");
                        BuryPointUtils.getInstance().trackViewScreen(getActivity(), "动态-最新", "com.cxzapp.yidianling.trends.trendList.TrendsListFragment");
                        break;
                    case 2:
                        BuryPointUtils.getInstance().createMap()
                                .put("toptab_name", "关注")
                                .burryPoint("topTabClick");
                        if (!DynamicIn.INSTANCE.isLogin()) {
                            startActivity(DynamicIn.INSTANCE.loginWayIntent(getActivity()));
                            return;
                        }
                        BuryPointUtils.getInstance().trackViewScreen(getActivity(), "动态-关注", "com.cxzapp.yidianling.trends.trendList.TrendsListFragment");
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if ("hot".equals(tab)) {
            vpContent.setCurrentItem(1);
            switchTab(1);
        } else if ("new".equals(tab)) {
            vpContent.setCurrentItem(0);
            switchTab(0);
        } else {
            vpContent.setCurrentItem(0);
            switchTab(0);
        }
    }


    private void switchTab(int index) {
        switch (index) {
            case 0:
                mItemRecommendTv.setSelected(false);
                mItemRecommendTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                mItemFocusTv.setSelected(false);
                mItemFocusTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                mItemHotTv.setSelected(true);
                mItemHotTv.setTextColor(getResources().getColor(R.color.dynamic_but_text_color));
                break;
            case 1:
                mItemRecommendTv.setSelected(true);
                mItemRecommendTv.setTextColor(getResources().getColor(R.color.dynamic_but_text_color));
                mItemFocusTv.setSelected(false);
                mItemFocusTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                mItemHotTv.setSelected(false);
                mItemHotTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                break;
            case 2:
                mItemRecommendTv.setSelected(false);
                mItemRecommendTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                mItemFocusTv.setSelected(true);
                mItemFocusTv.setTextColor(getResources().getColor(R.color.dynamic_but_text_color));
                mItemHotTv.setSelected(false);
                mItemHotTv.setTextColor(getResources().getColor(R.color.dynamic_text_666666));
                break;
        }
    }


    @OnClick({R2.id.trends_tv_mind_more, R2.id.publish_trend_btn, R2.id.item_recommend_tv, R2.id.item_hot_tv, R2.id.item_focus_tv})
    public void doClick(View view) {
        if (view.getId() == R.id.item_recommend_tv) {
            vpContent.setCurrentItem(1);
        } else if (view.getId() == R.id.item_hot_tv) {
            vpContent.setCurrentItem(0);
        } else if (view.getId() == R.id.item_focus_tv) {
            vpContent.setCurrentItem(2);
        } else if (view.getId() == R.id.publish_trend_btn) {
            if (!DynamicIn.INSTANCE.isLogin()) {
                startActivity(DynamicIn.INSTANCE.loginWayIntent(getActivity()));
            } else {
                Intent intent = new Intent(getActivity().getApplicationContext(), PublishTrendActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString(DynamicConstants.PUBLISH_TYPE, "default_publish");
//                intent.putExtra("bundle", bundle);
                //默认改为今日打卡
                Bundle bundle = new Bundle();
                bundle.putString(DynamicConstants.PUBLISH_TYPE, "topic_publish");
                bundle.putString("topic_id", "44");
                bundle.putString("topic_title", "今日打卡");
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        } else if (view.getId() == R.id.trends_tv_mind_more) {
            Intent intent = new Intent(getActivity(), AllTopicActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
//        else if (view.getId() == R.id.iv_background) {
//            YDLRouterManager.Companion.router(IYDLRouterConstant.ROUTER_FM_LIST);
//        }
    }

    @Override
    public void onFetchedDatas(Fragment[] fragments) {
        mFragments = fragments;
        initViewPager();
    }

    public void setBannerData(List<TrendsListBean.Banner> list) {
        v_banner.initData(list);
    }

    @Override
    public void onFetchedDataFailed() {

    }

    public void displayShowCase() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }


    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onRefresh() {
        swl.setRefreshing(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ((TrendsContentListFragment) mFragments[vpContent.getCurrentItem()]).onRefresh();
                swl.setRefreshing(false);
            }
        }, 300);
    }

    public void showMindsGroup(TopicListDataBean topicListDatas) {
        if (topicListDatas.list == null || topicListDatas.list.size() <= 0) {
            return;
        }
        for (int i = 0; i < 3 && i < topicListDatas.list.size(); i++) {
            switch (i) {
                case 0:
                    GlideApp.with(getActivity())
                            .load(topicListDatas.list.get(i).getImg_bg_url())
                            .centerCrop()
                            .transform(new RoundedCornersTransformation(20, 0, RoundedCornersTransformation.CornerType.LEFT))
                            .into(topicRoundIv1);
                    trendsTopicTv1.setText(topicListDatas.list.get(i).getTopic_title());
                    frlTopicIv1.setOnClickListener(view -> {
                        mindTopicClick(topicListDatas.list.get(0).getTopic_title(), topicListDatas.list.get(0).getTopic_id());
                    });
                    break;
                case 1:
                    GlideApp.with(getActivity())
                            .load(topicListDatas.list.get(i).getImg_bg_url())
                            .centerCrop()
                            .transform(new RoundedCornersTransformation(20, 0, RoundedCornersTransformation.CornerType.TOP_RIGHT))
                            .into(topicRoundIv2);
                    trendsTopicTv2.setText(topicListDatas.list.get(i).getTopic_title());
                    frlTopicIv2.setOnClickListener(view -> {
                        mindTopicClick(topicListDatas.list.get(1).getTopic_title(), topicListDatas.list.get(1).getTopic_id());
                    });
                    break;
                case 2:
                    GlideApp.with(getActivity())
                            .load(topicListDatas.list.get(i).getImg_bg_url())
                            .centerCrop()
                            .transform(new RoundedCornersTransformation(20, 0, RoundedCornersTransformation.CornerType.BOTTOM_RIGHT))
                            .into(topicRoundIv3);
                    trendsTopicTv3.setText(topicListDatas.list.get(i).getTopic_title());
                    frlTopicIv3.setOnClickListener(view -> {
                        mindTopicClick(topicListDatas.list.get(2).getTopic_title(), topicListDatas.list.get(2).getTopic_id());
                    });
                    break;
            }
        }


    }

    private void mindTopicClick(String title, String id) {
        BuryPointUtils.getInstance().createMap()
                .put("theme_name", title)
                .put("theme_ID", id)
                .burryPoint("Theme_click");
        Intent intent = new Intent();
        intent.setClass(getActivity(), TopicDetailActivity.class);
        intent.putExtra("topic_id", id);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getActivity().startActivity(intent);
    }

    public void showTopTrend(List<TrendsListBean.ExtData> extDatas) {
        mLooperTextView.setTipList(extDatas);
    }

}
