package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.model.entity.ArticleTag;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ApiKey;

import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.FIND_TAG;

/**
 * Created by realicing on 2018/6/27.
 * realicing@sina.com
 * 主页--发现模块
 */
public class FgtFind extends BaseFragment {
    private Activity activity;

    @Override
    public int getLayoutId() {
        return R.layout.fgt_find;
    }

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
    }

    @BindView(R.id.indicator)
    TabLayout indicator;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.add_article)
    View add_article;
    @BindView(R.id.add_article_expand)
    ImageView add_article_expand;
    @BindView(R.id.add_article_iv)
    ImageView add_article_iv;
    @BindView(R.id.add_article_camera)
    ImageView add_article_camera;
    @BindView(R.id.add_article_pic)
    ImageView add_article_pic;

    private TitleFragmentListAdapter mAdapter;

    private void initView() {
        mAdapter = new TitleFragmentListAdapter(getChildFragmentManager());
        mAdapter.add(FgtFindChild.newInstance(0), "全部");
        //悬浮
        ViewUtil.setImage(add_article_expand, ViewUtil.getNetImgByName("add_article_expand"));
        if(!onlyChooseVideo) {
            ViewUtil.setImage(add_article_iv, ViewUtil.getNetImgByName("add_article"));
            ViewUtil.setImage(add_article_camera, ViewUtil.getNetImgByName("add_article_camera"));
            ViewUtil.setImage(add_article_pic, ViewUtil.getNetImgByName("add_article_pic"));
        }
        ViewUtil.setVisibility(add_article, false);
        ViewUtil.setVisibility(add_article_iv, false);
        ViewUtil.setVisibility(add_article_camera, false);
        ViewUtil.setVisibility(add_article_pic, false);
        add_article.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(onlyChooseVideo) {
                    Jump2View.getInstance().gotoActPublishArticle(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
                } else {
                    changeAddArticle(add_article_iv.getVisibility() == View.VISIBLE);
                }
            }
        });
        if(!onlyChooseVideo) {
            add_article_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                changeAddArticle(true);
//                G.showToast("添加视频");
                    Jump2View.getInstance().gotoActPublishArticle(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
                }
            });
            add_article_pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                changeAddArticle(true);
//                G.showToast("添加图片");
                    Jump2View.getInstance().gotoActPublishArticle(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE);
                }
            });
        }
    }

    private boolean onlyChooseVideo = true;//只选择视频
    private void changeAddArticle(boolean isExpand) {
        ViewUtil.setVisibility(add_article_iv, !isExpand);
        ViewUtil.setVisibility(add_article_camera, !isExpand);
        ViewUtil.setVisibility(add_article_pic, !isExpand);
        add_article_expand.setAlpha(isExpand ? 1.0f : 0.0f);
    }

    private void initData() {
        //尝试获取缓存数据
        List<ArticleTag> newList = DataUtil.getInstance().getCacheList(ApiKey.articles_tags, ArticleTag.class);
        if (ListUtil.isEmpty(newList)) {
            initNetData();
        } else {
            loadList(newList);
        }
    }

    @Override
    public void initDataOnVisibleToUser() {
        if (list.isEmpty()) {
            try {
                initData();
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
    }

    private boolean isFirstOnResume = true;//第一次onResume

    @Override
    public void onResume() {
        super.onResume();
        if (list.isEmpty() && !isFirstOnResume) {//非第一次时并且没有数据时调用该接口
            try {
                initData();
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
        isFirstOnResume = false;
    }

    private void initNetData() {
        SheepApp.getInstance().getNetComponent().getApiService().getFindTagList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<ArticleTag> newList = baseMessage.getDatas(ArticleTag.class);
                        if (list.isEmpty() && !ListUtil.isEmpty(newList))//有缓存时不会加载，没有缓存时获取到数据会加载
                            loadList(newList);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                    }
                });
    }

    //没有添加数据返回true
    private void loadList(List<ArticleTag> newList) {
        if (!ListUtil.isEmpty(newList)) {
            list.clear();
            ListUtil.addAll(list, newList);
            CommonUtil.getInstance().initUrlConfigByNet("awaken_on", new Action1<String>() {
                @Override
                public void call(String url) {
                    int awaken_on = NumberFormatUtils.parseInteger(url);
                    int count = 1;
                    for (ArticleTag findLabel : list) {
                        switch (findLabel.getName()) {
                            case "视频":
                                mAdapter.add(FgtArticleVideo.newInstance(findLabel.getId()), findLabel.getName());
                                break;
                            default:
                                mAdapter.add(FgtFindChild.newInstance(findLabel.getId()), findLabel.getName());
                                break;
                        }
                        count++;
                    }
                    if (awaken_on == 1) {
                        count++;
                        mAdapter.add(new FgtWatchFocus(), "看点", 2);
                    }
                    pager.setAdapter(mAdapter);
                    indicator.setupWithViewPager(pager);
                    pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int i, float v, int i1) {

                        }

                        @Override
                        public void onPageSelected(int i) {
                            ViewUtil.setVisibility(add_article, mAdapter.getItem(i) instanceof FgtArticleVideo);
                            FIND_TAG.onEvent("find_tag_name", ListUtil.hasIndex(list, i - 1) ? list.get(i - 1).getName() : "全部");
                        }

                        @Override
                        public void onPageScrollStateChanged(int i) {

                        }
                    });
                    CommonUtil.getInstance().reflex(indicator, activity);
                    pager.setOffscreenPageLimit(count);

                }
            });
        }
    }

    private List<ArticleTag> list = ListUtil.emptyList();

}
