package com.kfzs.duanduan.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.kfzs.appstore.utils.adapter.recyclerview.DividerItemDecoration;
import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.ActGategoryRank;
import com.sheep.jiuyan.samllsheep.R;
import com.kfzs.duanduan.adp.AdpFragmentRank;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.bean.RecyleObj;
import com.kfzs.duanduan.bean.RecyleType;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.event.EventDownloadHandler;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.GameOuterClass;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.utils.dlg.DownBtnUtils;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.utils.dlg.ViewFindUtils;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.view.FilterWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;


/**
 * 分类排行榜
 * <p/>
 * Created by HooRang on 2017/2/16.
 */
public class CategoryRankFragment extends BaseCompatFragment {

    private static final String TAG = CategoryRankFragment.class.getName();

    private AdpFragmentRank mAdpFragmentRank;

    private RecyclerView mRecyclerView;
    private FilterWindow mFilterWindow;

    private Button mBtnTypeChoose;
    private EventDownloadHandler.OnDownCallback mOnDownCallback;
    private int gameType = 0;

    private Activity activity;
    @Override
    protected void initView(Bundle savedInstanceState) {
        activity = getActivity();
        EventBus.getDefault().register(this);

        setContentView(R.layout.fragment_game_lists_common);
        Bundle bundle = getArguments();
        if(bundle != null){
            gameType = bundle.getInt(ActGategoryRank.INTENT_TYPE_ID);
        }

        mRecyclerView = ViewFindUtils.find(mContentView, R.id.recy_fgt_main_game);
        //隐藏空空如也
        ViewFindUtils.find(mContentView, R.id.empty_view).setVisibility(View.GONE);
        mAdpFragmentRank = new AdpFragmentRank(activity, mRecyclerView, ClsTypeChoose);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        DividerItemDecoration decor = new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
        decor.setIsShowFirstItemDecoration(false);
        decor.setSize(getResources().getDimensionPixelOffset(R.dimen.app_list_item_divider_size));
        decor.setColor(getResources().getColor(R.color.theme_app_divider_color));
        decor.setPaddingStart(getResources().getDimensionPixelOffset(R.dimen.app_list_item_divider_start_image));
        decor.setPaddingEnd(getResources().getDimensionPixelOffset(R.dimen.app_list_item_divider_end));
        mRecyclerView.addItemDecoration(decor);
        mRecyclerView.setAdapter(mAdpFragmentRank);

        //首次载入数据
        doNetworkTask(gameType ==0?"":gameType+"");
    }

    @Override
    public void refreshData() {
        doNetworkTask("");
    }


    /**
     * 选择分类的监听
     */
    private View.OnClickListener ClsTypeChoose = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mBtnTypeChoose = (Button) v;
            showFilterPanel(mBtnTypeChoose);
            mBtnTypeChoose.setCompoundDrawablesWithIntrinsicBounds(
                    R.mipmap.btn_query_condition_left_ing, 0, R.mipmap.arrow_top, 0);
        }
    };

    /**
     * 展开分类选择板块
     *
     * @param anchor
     */
    private void showFilterPanel(View anchor) {
        if (null == mFilterWindow) {
            mFilterWindow = new FilterWindow(mContext, anchor, new FilterWindow.OnPopupWinListener() {
                @Override
                public void onReset() {
                    doNetworkTask("");
                }

                @Override
                public void onSubmit(String selectedIndexs) {
                    Log.d(TAG, "selectedIndexs#" + selectedIndexs);
                    doNetworkTask(selectedIndexs);
                }

                @Override
                public void dismiss() {
                    mBtnTypeChoose.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.btn_query_condition_left_ing, 0, R.mipmap.arrow_bottom, 0);
                }
            });
        }
        mFilterWindow.createWindow().show();
    }


    /**
     * 加载本页数据
     *
     * @param selectedIndexs
     */
    private void doNetworkTask(final String selectedIndexs) {
        HashMap<String, String> params = new HashMap<>();
        params.put("page", UrlBll.AppStoreApi.PAGE_CATEGORY_RANK + "");
        if (!TextUtils.isEmpty(selectedIndexs)) {
            params.put("types", selectedIndexs);
        }

        APIRequest bannerRequest = APIRequestInstance.getReqUrl(TAG, UrlBll.AppStoreApi.GAME_LISTS, params, new ResponseNetworkTask() {
            @Override
            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                refreshOver();
                mAdpFragmentRank.clear();
//                mAdpFragmentRank.add(RecyleObj.make(RecyleType.RANK_TYPE, null));
                mAdpFragmentRank.add(RecyleObj.make(RecyleType.RANK_TOP3, apiResponse.getGameList().getTopThreeGamesList()));
                for (GameOuterClass.Game game : apiResponse.getGameList().getOtherGamesList()) {
                    mAdpFragmentRank.add(RecyleObj.make(RecyleType.RANK_LIST, game));
                }
                mAdpFragmentRank.notifyDataSetChanged();
            }

            @Override
            public void onFail(int code, String msg) {
                refreshOver();
            }

        }, HelperUtils.makeErr(getString(R.string.toast_init_data_fail)));
        KFZSNetwork.addRequest(bannerRequest);
    }


    /**
     * TODO 小刁，这里感觉以后应该可以删除
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            refreshOver();
        }
    }

    /**
     * 把更新放到Logic里了，代码少一半以上。
     *
     * @param info
     */
    @Subscribe
    public void onEventMainThread(DownloadStatus info) {
        if (mOnDownCallback == null) {
            mOnDownCallback = DownBtnUtils.installBtnStatus(mAdpFragmentRank.getmDownLoadItemLogicMgrMap());
        }
        EventDownloadHandler
                .newInstance(activity, mOnDownCallback)
                .setmTag(TAG)
                .handlDownloadResult(info);
    }


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