package com.kfzs.duanduan.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.android.volleyplus.Response;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kf.utils.KFLog;
import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.InstallButtonUtils;
import com.kfzs.duanduan.view.KFProgressButton;
import com.sheep.jiuyan.samllsheep.R;
import com.kfzs.duanduan.adp.AdpMainPageRecy;
import com.kfzs.duanduan.bean.BaseMsg;
import com.kfzs.duanduan.bean.CateGameList;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.bean.GuessYouLike;
import com.kfzs.duanduan.bean.NewGameRecommend;
import com.kfzs.duanduan.bean.RecyleObj;
import com.kfzs.duanduan.bean.RecyleType;
import com.kfzs.duanduan.bean.SpecialRecommend;
import com.kfzs.duanduan.bll.GameListBll;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.event.EventDownloadHandler;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.IndexAllbannerOuterClass;
import com.kfzs.duanduan.proto.IndexGameOuterClass;
import com.kfzs.duanduan.utils.dlg.DownBtnUtils;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;

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

import java.io.File;
import java.util.Map;

import static android.content.Intent.ACTION_PACKAGE_ADDED;
import static android.content.Intent.ACTION_PACKAGE_REMOVED;


/**
 * @ Created by Dlg
 * @ <p>TiTle:  FgtMainGame</p>
 * @ <p>Description: 首页Fragment的游戏一栏</p>
 * @ date:  2017/6/14 13:39
 * @ QQ:    315096953
 */
public class FgtMainGame extends BaseCompatFragment {


    private RecyclerView mRecyView;
    private IndexAllbannerOuterClass.IndexAllbanner mAllBannerDatas;
    private AdpMainPageRecy mAdpMainPageRecy;
    private EventDownloadHandler.OnDownCallback mOnDownCallback;
    private static final int POS_BANNER = 0;
    private static final int POS_OWN = 1;//专属栏
//    private static final int POS_THREE = 2;//三玩栏
    private static final int POS_NEW_GAME_BANNER = 2;//新游预的banner
    private static final int POS_NEW_GAME_RECOMMEND = 3;//新游推荐的列表
    private static final int POS_GUESS_YOU_LIKE = 4;//猜你喜欢
    private static final int POS_SPECIAL_RECOMMEND = 5;//特别推荐
    private static final int POS_COUPON = 6;//优惠券
    private static final int POS_RPG = 7;//角色扮演
    private static final int POS_SUBJECT = 8;//专题
    private static final int POS_CARTON = 9;//二次元
    private static final int POS_BACK_TOP = 10;//返回到顶部
    SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    protected void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        setContentView(R.layout.fgt_main_game);
        mRecyView = mContentView.findViewById(R.id.recy_fgt_main_game);
        mSwipeRefreshLayout = mContentView.findViewById(R.id.refresh);
        mRecyView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdpMainPageRecy = new AdpMainPageRecy(getActivity(), mRecyView);
        for (int i = 0; i < 12; i++) {
            mAdpMainPageRecy.add(RecyleObj.make(RecyleType.NONE, null));
        }
        mRecyView.setAdapter(mAdpMainPageRecy);
        loadDatas();

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
        Aria.download(this).register();

    }

    @Override
    public void refreshData() {
        loadDatas();
    }


    /**
     * 加载本fragment数据
     */
    private void loadDatas() {
        APIRequest bannerRequest = APIRequestInstance.getReq(TAG, UrlBll.AppStoreApi.BANNER, null, new Response.Listener<ApiResponseOuterClass.ApiResponse>() {


            @Override
            public void onResponse(ApiResponseOuterClass.ApiResponse apiResponse) {

                int code = apiResponse.getCodeValue();
                switch (code) {
                    case ApiResponseOuterClass.Codes.Success_VALUE:
                        mAllBannerDatas = apiResponse.getIndexAllbanner();
                        loadGameLists();
                        break;
                    default:
                        KFLog.e("首页Banner加载失败#" + code);
                        refreshOver();
                        break;
                }

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

        GameListBll gameListBll = new GameListBll();
        //加载新游推荐列表
        gameListBll.getNewGameRecommendList(null, 10, new Response.Listener<BaseMsg>() {
            @Override
            public void onResponse(BaseMsg baseMsg) {
                if (baseMsg.getDatas(NewGameRecommend.class) == null
                        || baseMsg.getDatas(NewGameRecommend.class).size() < 1) {
                    return;
                }
                mAdpMainPageRecy.add(RecyleObj.make(RecyleType.NEW_GAME_RECOMMEND,
                        baseMsg.getDatas(NewGameRecommend.class)), POS_NEW_GAME_RECOMMEND);
                mAdpMainPageRecy.notifyItemChanged(POS_NEW_GAME_RECOMMEND);
            }
        });

        //加载猜你喜欢一栏

        gameListBll.getGuessYouLike(new Response.Listener<BaseMsg>() {
            @Override
            public void onResponse(BaseMsg baseMsg) {
                if (baseMsg.getData(GuessYouLike.class) == null) {
                    return;
                }
                mAdpMainPageRecy.add(RecyleObj.make(RecyleType.GUESS_YOU_LIKE,
                        baseMsg.getData(GuessYouLike.class)), POS_GUESS_YOU_LIKE);
                //TODO 暂时原因不明，如果局部加载，始终会第一次加载不出来。。。
//                mAdpMainPageRecy.notifyItemChanged(POS_GUESS_YOU_LIKE);
                mAdpMainPageRecy.notifyDataSetChanged();
            }
        });

        //加载特别推荐
        gameListBll.getSpecialRecommend(new Response.Listener<BaseMsg>() {
            @Override
            public void onResponse(BaseMsg baseMsg) {
                if (baseMsg.getData(SpecialRecommend.class) == null) {
                    return;
                }
                mAdpMainPageRecy.add(RecyleObj.make(RecyleType.SPECIAL_GAME_RECOMMEND,
                        baseMsg.getData(SpecialRecommend.class)), POS_SPECIAL_RECOMMEND);
                mAdpMainPageRecy.notifyItemChanged(POS_SPECIAL_RECOMMEND);
            }
        });

        //加载专题二次元和角色扮演
        gameListBll.getCartonRPGEtc(new Response.Listener<BaseMsg>() {
            @Override
            public void onResponse(BaseMsg baseMsg) {
                CateGameList gameList = baseMsg.getData(CateGameList.class);
                if (gameList == null) {
                    return;
                }
                if (gameList.getCommon() != null && gameList.getCommon().size() > 0) {
                    mAdpMainPageRecy.add(RecyleObj.make(RecyleType.RPG,
                            gameList.getCommon().get(0)), POS_RPG);
                }
                if (gameList.getCommon() != null && gameList.getCommon().size() > 1) {
                    mAdpMainPageRecy.add(RecyleObj.make(RecyleType.CARTON,
                            gameList.getCommon().get(1)), POS_CARTON);
                }
                if (gameList.getSubject() != null
                        && gameList.getSubject().getGames().size() > 0) {
                    mAdpMainPageRecy.add(RecyleObj.make(RecyleType.SUBJECT,
                            gameList.getSubject()), POS_SUBJECT);
                }
                mAdpMainPageRecy.notifyItemChanged(POS_SUBJECT);
            }
        });

    }


    /**
     * 加载游戏列表
     */
    private void loadGameLists() {
        try {
            APIRequest bannerRequest = APIRequestInstance.getReq(TAG, UrlBll.AppStoreApi.RECOMMEND_GAME_GROUPS, null, new Response.Listener<ApiResponseOuterClass.ApiResponse>() {

                @Override
                public void onResponse(ApiResponseOuterClass.ApiResponse apiResponse) {
                    int code = apiResponse.getCodeValue();
                    switch (code) {
                        case ApiResponseOuterClass.Codes.Success_VALUE:
                            IndexGameOuterClass.IndexGame indexGame = apiResponse.getIndexGame();
                            loadViews(indexGame);
                            break;
                        default:
                            break;
                    }
                    refreshOver();

                }
            }, HelperUtils.makeErr(getString(R.string.toast_init_data_fail)));
            KFZSNetwork.addRequest(bannerRequest);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 加载视图，以前是一个接口就有了recyview的所有值，所以用了dataObj
     * 现改为多个接口，所以值就在adp里再去分别获取吧,dataObj不用了。
     *
     * @param indexGame
     */
    private void loadViews(IndexGameOuterClass.IndexGame indexGame) {

        if (mAllBannerDatas.getShufflingList() != null &&
                !mAllBannerDatas.getShufflingList().isEmpty()) {
            mAdpMainPageRecy.add(RecyleObj.make(RecyleType.BANNER,
                    mAllBannerDatas.getShufflingList()), POS_BANNER);
        }
//        mAdpMainPageRecy.add(RecyleObj.make(RecyleType.OWN_ZONE, null), POS_OWN);//VIP专区
//        mAdpMainPageRecy.add(RecyleObj.make(RecyleType.THREE_PLAY, null), POS_THREE);
        mAdpMainPageRecy.add(RecyleObj.make(RecyleType.BACK_TOP, null), POS_BACK_TOP);

        System.gc();
        mAdpMainPageRecy.notifyDataSetChanged();
    }

    /**
     * 把更新放到Logic里了，代码少一半以上。
     *
     * @param info
     */
    @Subscribe
    public void onEventMainThread(DownloadStatus info) {
        if (mOnDownCallback == null) {
            mOnDownCallback = DownBtnUtils.installBtnStatus(mAdpMainPageRecy.getmDownLoadItemLogicMgrMap());
        }
        EventDownloadHandler
                .newInstance(getActivity(), mOnDownCallback)
                .setmTag(TAG)
                .handlDownloadResult(info);
    }
//        if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) || Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) || Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){
    @Subscribe
    public void onEventMainThread(Intent intent) {
        if(intent != null && intent.getAction() != null && intent.getDataString() != null && intent.getDataString().contains("package:")){
            String packageName = intent.getDataString().replace("package:","");
            for (Map.Entry<String, InstallButtonUtils> entry : mAdpMainPageRecy.getmDownLoadItemLogicMgrMap().entrySet()) {
                if(packageName.equals(entry.getValue().getPackageName())){
                    switch (intent.getAction()){
                        case ACTION_PACKAGE_ADDED:
                            entry.getValue().setStatus(KFProgressButton.STATUS.STATUS_FINISH);
                            return;
                        case ACTION_PACKAGE_REMOVED:
                            if(new File(ClassFileHelper.getFilePathByPackageName(packageName)).exists()) {
                                entry.getValue().setStatus(KFProgressButton.STATUS.STATUS_FINISH);
                            } else {
                                entry.getValue().setStatus(KFProgressButton.STATUS.STATUS_INIT);
                            }
                            return;
                    }
                }
            }
        }
    }


    @Download.onPre void onPre(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_INIT);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }
    @Download.onTaskStart void taskStart(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_ING);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_ING);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_ING);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_PAUSE);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_DELETE);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_FAIL);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        DownloadStatus downloadStatus = new DownloadStatus();
        downloadStatus.setStatus(DownloadTaskService.STATUS_FINISH);
        downloadStatus.setApkPath(task.getDownloadPath());
        downloadStatus.setDownloadUrl(task.getKey());
        onEventMainThread(downloadStatus);
    }


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