package com.sheep.gamegroup.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.StatusBarUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sheep.gamegroup.absBase.AbsGetDownloadListener;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.ILoadMore;
import com.sheep.gamegroup.absBase.IRefresh;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.helper.DownloadHelper;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.entity.GameListTag;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiUtil;
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.RefreshUtil;
import com.sheep.gamegroup.util.RequestCodeConstants;
import com.sheep.gamegroup.util.TagListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter2;
import com.sheep.gamegroup.view.fragment.FgtGcGameAppComment;
import com.sheep.gamegroup.view.fragment.FgtGcGameAppDetail;
import com.sheep.gamegroup.view.fragment.FgtGcGameAppWelfare;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Locale;

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

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


/**
 * Created by realicing on 2018/10/31.
 * realicing@sina.com
 * 新的游戏详情界面
 */
public class ActGcGameAppDetail extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTranslucent(this);
        super.onCreate(savedInstanceState);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.act_gc_game_app_detail;
    }

    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.gc_game_app_detail_iv)
    ImageView gc_game_app_detail_iv;
    @BindView(R.id.gc_game_app_detail_iv2)
    ImageView gc_game_app_detail_iv2;
    @BindView(R.id.gc_game_app_detail_play_iv)
    ImageView gc_game_app_detail_play_iv;
    @BindView(R.id.gc_game_app_detail_icon)
    ImageView gc_game_app_detail_icon;
    @BindView(R.id.write_comment)
    ImageView write_comment;
    @BindView(R.id.gc_game_app_detail_bt1)
    TextView gc_game_app_detail_bt1;
    @BindView(R.id.gc_game_app_detail_name)
    TextView gc_game_app_detail_name;
    @BindView(R.id.gc_game_app_detail_bt2)
    TextView gc_game_app_detail_bt2;
    @BindView(R.id.gc_game_app_detail_tag_list)
    RecyclerView recyclerView;

    private TitleFragmentListAdapter2 mAdapter;
    private FgtGcGameAppDetail fgtGcPlayGameDetail;
    private FgtGcGameAppComment fgtGcGameAppComment;

    private int id;
    @Override
    public void initView() {
        id = getIntent().getIntExtra("id", 0);
        EventBus.getDefault().register(this);
        //tagList
        TagListUtil.setTagList(recyclerView, tagList);
        //viewPager
        mAdapter = new TitleFragmentListAdapter2(getSupportFragmentManager());
        fgtGcPlayGameDetail = FgtGcGameAppDetail.newInstance(id);
        fgtGcGameAppComment = FgtGcGameAppComment.newInstance(id);
        fgtGcPlayGameDetail.setSmartRefreshLayout(refresh);
        fgtGcGameAppComment.setSmartRefreshLayout(refresh);
        fgtGcGameAppComment.setListAction1(fgtGcPlayGameDetail);
        mAdapter.add(fgtGcPlayGameDetail, "详情");
        mAdapter.add(fgtGcGameAppComment, "评价");
        viewPager.setOffscreenPageLimit(mAdapter.getCount());
        viewPager.setAdapter(mAdapter);
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
        tabLayout.setupWithViewPager(viewPager);
        CommonUtil.getInstance().reflex(tabLayout, this);
        //refresh
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }
        });
        RefreshUtil.newInstance().publicParameterLoadMore(refresh, this);

        ViewUtil.setImage(write_comment, ViewUtil.getNetImgByName("write_comment"));
    }

    private List<GameListTag> tagList = ListUtil.emptyList();

    //重置view
    private void resetView() {
        ViewUtil.setDefaultText(gc_game_app_detail_name);
    }

    //检查数据
    private void checkData(GameEntity gameEntity) {
        if (gameEntity != null && gameEntity.getApp() != null) {
            loadData(gameEntity);
        } else {
            resetView();
        }
    }

    private GameEntity gameEntity;

    //更新关注状态
    private void updateFocusTv() {
        if(gc_game_app_detail_bt1 != null && gameEntity != null)
            gc_game_app_detail_bt1.setText(gameEntity.isIs_focus_game() ? R.string.has_focus : R.string.focus);
    }
    //加载游戏数据
    private void loadData(final GameEntity gameEntity) {
        this.gameEntity = gameEntity;
        //更新关注状态
        updateFocusTv();
        tryInitWelfare();
        //更新评价数量
        if(gameEntity.getApp().getComment_num() > 0) {
            TabLayout.Tab tab = tabLayout.getTabAt(1);
            if (tab != null)
                tab.setText(String.format(Locale.CHINA, "评价(%d)", gameEntity.getApp().getComment_num()));
            CommonUtil.getInstance().reflex(tabLayout, this, true);
        }
        //加载游戏背景
        if(TextUtils.isEmpty(gameEntity.getApp().getMain_publicize())){
            ViewUtil.setImage(gc_game_app_detail_iv, gameEntity.getApp().getPictures());
            ViewUtil.setVisibility(gc_game_app_detail_iv, true);
            ViewUtil.setVisibility(gc_game_app_detail_iv2, false);
        } else {
            ViewUtil.setImage(gc_game_app_detail_iv2, gameEntity.getApp().getMain_publicize());
            ViewUtil.setVisibility(gc_game_app_detail_iv, false);
            ViewUtil.setVisibility(gc_game_app_detail_iv2, true);
            if(gameEntity.getApp().getMain_publicize().endsWith(".mp4")) {
                gc_game_app_detail_play_iv.setVisibility(View.VISIBLE);
                gc_game_app_detail_play_iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Jump2View.getInstance().goActPlayVideo(gameEntity.getApp().getMain_publicize(), true);
                    }
                });
            }
        }
        //加载游戏图标
        ViewUtil.setGameImage(gc_game_app_detail_icon, gameEntity.getApp().getIcon());
        //加载游戏名字
        ViewUtil.setText(gc_game_app_detail_name, gameEntity.getApp().getName());
        //加载游戏标签
        if(gameEntity.getApp().getTags() != null) {
            tagList.addAll(gameEntity.getApp().getTags());
            ListUtil.removeNull(tagList);
            if(recyclerView.getAdapter() != null)
                recyclerView.getAdapter().notifyDataSetChanged();
        }
        //下载按钮
        CommonUtil.getInstance().palyGameDetailBtnValue(this, gameEntity, gc_game_app_detail_bt2, 0);
        fgtGcPlayGameDetail.loadData(gameEntity);
    }

    private FgtGcGameAppWelfare fgtGcGameAppWelfare;
    //重新初始化viewPager的数据
    private void tryInitWelfare() {
        if(fgtGcGameAppWelfare != null || !gameEntity.isGift()){
            return;
        }
        fgtGcGameAppWelfare = FgtGcGameAppWelfare.newInstance(id);
        fgtGcGameAppWelfare.setSmartRefreshLayout(refresh);
        fgtGcGameAppWelfare.loadData(gameEntity);
        mAdapter.add(fgtGcGameAppWelfare, "福利");
        mAdapter.notifyDataSetChanged();
        viewPager.setOffscreenPageLimit(mAdapter.getCount());
    }

    //通过网络获取游戏数据并尝试加载
    private void initDetailFromNet() {
        SheepApp.getInstance().getNetComponent().getApiService().playGameDetail(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(this) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.playGameDetail(id));
                        if (isNewData) {
                            GameEntity gameEntity = baseMessage.getData(GameEntity.class);
                            checkData(gameEntity);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        resetView();
                    }
                });
    }

    @Override
    public void initData() {
        GameEntity gameEntity = DataUtil.getInstance().getCacheResult(ApiKey.playGameDetail(id), GameEntity.class);
        checkData(gameEntity);
        refreshData();
    }

    private int refreshDataCount = 0;
    //刷新数据
    public void refreshData(){
        refreshData(viewPager.getCurrentItem());
    }
    //刷新数据
    public void refreshData(int position){
        initDetailFromNet();
        boolean isRefresh = false;
        if (refreshDataCount != 0) {
            Fragment item = mAdapter.getItem(position);
            if (item instanceof IRefresh) {//可刷新，就调用当前fragment刷新数据
                ((IRefresh) item).refreshData();
                isRefresh = true;
            }
        }
        refreshDataCount++;
        if(!isRefresh)
            notifyDataSetChanged();
    }
    //加载更多数据
    private void loadMoreData() {
        Fragment item = mAdapter.getItem(viewPager.getCurrentItem());
        if (item instanceof ILoadMore) {//可加载更多，就调用当前fragment刷新数据
            ((ILoadMore) item).loadMoreData();
        } else {
            notifyDataSetChanged();
        }
    }

    private void notifyDataSetChanged() {
        if (refresh != null) {
            refresh.finishRefresh();
            refresh.finishLoadMore();
        }
    }

    //点击返回
    public void onClickBackImg(View view) {
        finish();
    }

    //点击分享
    public void onClickShareImg(View view) {
        FIND_SHARE.onEvent("application_id", id);
        if(gameEntity == null || gameEntity.getApp() == null || TextUtils.isEmpty(gameEntity.getApp().getName())){
            Jump2View.getInstance().tryShare(this, "find_share_url", "application_id", id);
            return;
        }
        Jump2View.getInstance().tryShare(this, "find_share_url", "application_id", id, String.format(Locale.CHINA, "【%s】超好玩，来小绵羊一起玩", gameEntity.getApp().getName()));
    }

    //点击加，发表评论
    public void onClickPlusDrag(View view) {
        Jump2View.getInstance().goActCommentGameApp(this, id);
    }

    //点击关注
    public void onClickFollowTv(final View view) {
        if(gameEntity == null){
            G.showToast(R.string.loading_data);
            return;
        }
        view.setEnabled(false);
        ApiUtil.postGameUserFocusGame(id, new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
            @Override
            public void onNext(BaseMessage baseMessage) {
                G.showToast(gameEntity.isIs_focus_game() ? R.string.cancel_focus_success : R.string.focus_success);
                gameEntity.setIs_focus_game(!gameEntity.isIs_focus_game());
                updateFocusTv();
                view.setEnabled(true);
            }

            @Override
            public void onError(BaseMessage baseMessage) {
                G.showToast(gameEntity.isIs_focus_game() ? R.string.cancel_focus_fail : R.string.focus_fail);
                view.setEnabled(true);
            }
        });
    }

    private AbsGetDownloadListener absGetDownloadListener = new AbsGetDownloadListener(true) {
        @Override
        public String getDownloadUrl(String packageName) {
            return gameEntity != null ? gameEntity.getDownloadUrl(packageName) : null;
        }

        @Override
        public TextView getTextView2(String packageName) {
            return getDownloadUrl(packageName) != null ? gc_game_app_detail_bt2 : null;
        }

        @Override
        public TextView getTextView(String downloadUrl) {
            return gameEntity != null && TextUtils.equals(downloadUrl, gameEntity.downLinks()) ? gc_game_app_detail_bt2 : null;
        }

        @Override
        public DownloadHelper getDownloadHelper(String downloadUrl) {
            return gameEntity != null ? gameEntity.getDownloadHelper(downloadUrl) : null;
        }
    };

    @Subscribe
    public void onEventMainThread(Intent intent) {
        absGetDownloadListener.onEventMainThread(intent);
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        absGetDownloadListener.onEventMainThread(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case RequestCodeConstants.REQUEST_CODE_REFRESH:
                if(resultCode == RESULT_OK)//发表评论成功
                    refreshData(1);//需要刷新第二页的评论
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //点击领取福利
    public void onClickDownloadReceiveWelfare(View view) {
        //TODO 点击领取福利
        G.showToast(R.string.coming_soon);
    }
}
