package com.kfzs.duanduan;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volleyplus.Response;
import com.android.volleyplus.VolleyError;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.bumptech.glide.Glide;
import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.adp.AdpViewPagerDetail;
import com.kfzs.duanduan.bean.BaseMsg;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.kfzs.duanduan.bean.UserRecord;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventDownloadHandler;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.fragment.FgtGameDetail;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.GameOuterClass;
import com.kfzs.duanduan.utils.InstallButtonUtils;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.kfzs.duanduan.utils.ShareUtils;
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.kfzs.duanduan.utils.net.APIRequestV2;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.kfzs.duanduan.view.KFProgressButton;
import com.kfzs.duanduan.view.ViewPagerAutoHeigh;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;

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

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.kfzs.duanduan.bean.KFIntentKeys.EXTRA_PAGE_NUM;


/**
 * @ Created by Dlg
 * @ <p>TiTle:  ActGameDetails</p>
 * @ <p>Description: 商品详情页，已经重构了</p>
 * @ KFIntentKeys.EXTRA_GAME_ID 传商品Id
 * @ date:  2017/6/19 13:36
 * @ QQ:    315096953
 */
public class ActGameDetails extends BaseCompatActivity {

    private GameOuterClass.Game respGame;

    private Boolean bShowDownloadBtn = true;

    private String sGameId = "";
    private Map<String, InstallButtonUtils> mInstallButtonMgr = new HashMap<>();
    private UserRecord userRecord;

    private int selectType = 0;//选择tab项0,1,2


    @BindView(R.id.viewpager_act_game_details)
    ViewPagerAutoHeigh mViewPager;

    @BindView(R.id.img_act_game_details_logo)
    ImageView mGameIcon;

    @BindView(R.id.img_act_game_details_bg)
    ImageView mImgBg;

    @BindView(R.id.txt_act_game_details_name)
    TextView mGameName;

    @BindView(R.id.txt_act_game_details_types)
    TextView mGameTags;

    @BindView(R.id.img_back)
    View mBack;

    @BindView(R.id.img_share)
    View mShare;

    @BindView(R.id.txt_act_game_details_downcount)
    TextView mGameDldCnt;

    @BindView(R.id.ratb_act_game_details)
    RatingBar mGameStars;

    @BindView(R.id.downbtn_frg_fgt_app_detail_install)
    KFProgressButton mBtnDown;


    @BindView(R.id.toolbar_layout_act_game_details)
    CollapsingToolbarLayout collapsingToolbarLayout;

    @BindView(R.id.txt_act_game_details_title)
    TextView mTxtTitle;

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;

    private EventDownloadHandler.OnDownCallback mOnDownCallback;
    private FgtGameDetail mFragmentGameDetail;
    private boolean mIsExpanded = false;//是否是折叠状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_details_parent);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        bShowDownloadBtn = !getIntent().hasExtra(KFIntentKeys.EXTRA_GAME_REQUEST_ORDER);
        selectType = getIntent().getIntExtra(EXTRA_PAGE_NUM, 0);
        initView();
        initData();
        Aria.download(this).register();
    }

    private void initData() {
        Intent intent = getIntent();
        sGameId = intent.getStringExtra(KFIntentKeys.EXTRA_GAME_ID);
        loadLoanUserercord(sGameId);

        doNetworkTask(sGameId);
    }

    /**
     * 初始化各组件
     */
    private void initView() {
//        int height = HelperUtils.W * 310 / 720;
//        mImgBg.setLayoutParams(new RelativeLayout.LayoutParams(HelperUtils.W, height));

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar_act_game_details));
        if(mFragmentGameDetail == null){
            mFragmentGameDetail = new FgtGameDetail();
        }
        AdpViewPagerDetail adpViewPagerDetail = new AdpViewPagerDetail(getSupportFragmentManager());
        adpViewPagerDetail.add(mFragmentGameDetail, getString(R.string.app_details_details));
//        adpViewPagerDetail.add(new FgtGift(), getString(R.string.app_details_user_gift));//小绵羊中注释掉用户礼包
//        adpViewPagerDetail.add(new FgContinuePlay(), getString(R.string.continue_play));//小绵羊中注释掉借着玩
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(adpViewPagerDetail);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mViewPager.reSetHeight();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        /*
          标题显示和隐藏的监听
         */
        ((AppBarLayout) findViewById(R.id.appbar_act_game_details)).addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (Math.abs(verticalOffset) <
                        appBarLayout.getTotalScrollRange() - HelperUtils.getDpiToPix(20)) {
                    if (!mIsExpanded) {
                        mIsExpanded = true;//修改状态标记为展开
                        mTxtTitle.setVisibility(View.INVISIBLE);
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (mIsExpanded) {
                        mTxtTitle.setVisibility(View.VISIBLE);
                        mIsExpanded = false;//修改状态标记为折叠
                    }
                }
            }
        });

        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectType = tab.getPosition();
//                G.showToast(tab.getPosition()+","+tab.getText());
                Log.e("tab.getPosition()", tab.getPosition() + "");
                setButtonStatue(tab.getPosition());

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popShare();
            }
        });


        if (getIntent().hasExtra(EXTRA_PAGE_NUM)) {
            mViewPager.setCurrentItem(selectType);
        }
    }

    /**
     * 设置button状态
     */
    private void setButtonStatue(int position){
        if (position == 2) {
//                    mBtnDown.setVisibility(View.GONE);
            if (userRecord == null) {
                return;
            }
            if (userRecord.getLoan_state() == 2 && userRecord.getHave_access_state() == 2) {//不允许借款
//                        mBtnDown.setVisibility(View.GONE);
            } else {
//                        mBtnDown.setVisibility(View.VISIBLE);
                if (userRecord.getHave_access_state() == 2) {//未借款
                    mBtnDown.setText("去还款");
                } else {
                    mBtnDown.setText("去借款");
                }
            }
            mBtnDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    G.showToast(R.string.coming_soon);
                }
            });
        } else {
            if (!bShowDownloadBtn) {
                mBtnDown.setVisibility(View.GONE);
                return;
            }
            mBtnDown.setVisibility(View.VISIBLE);
            if (respGame == null) {
                return;
            }
//                    nestedScrollView.setNestedScrollingEnabled(true);
            try {
                DownBtnUtils.addDownloadBtnListener(mBtnDown, ActGameDetails.this,
                        mInstallButtonMgr, respGame, "game_detail" + respGame.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 分享游戏；
     */
    private void popShare() {
        String shareUrl;
        if (respGame != null && !TextUtils.isEmpty(respGame.getDownloadUrl())) {
            shareUrl = respGame.getDownloadUrl();
        } else if (respGame != null && !TextUtils.isEmpty(respGame.getBookDownloadUrl())) {
            shareUrl = respGame.getBookDownloadUrl();
        } else {
            showToast("分享地址错误！");
            return;
        }
        if (!TextUtils.isEmpty(shareUrl) && shareUrl.toLowerCase().startsWith("http")) {
            new ShareUtils().showShareView(this, shareUrl, respGame.getGameName(),
                    respGame.getIconImage(), respGame.getIntroduce());
        } else {
            String msg = "分享错误，请联系客服!\n错误链接为: " + shareUrl;
            Log.w("DD_ERROR", msg);
            showToast(msg);
        }
    }

    @Override
    public void onBackPressed() {
        if (KFZSApp.actMain == null) {
            Intent intent = new Intent(this, ActMain.class);
            startActivity(intent);
        }
        this.finish();
    }

    private void doNetworkTask(final String sGameId) {

        String reqUrl = UrlBll.AppStoreApi.GAME_LISTS + "/" + sGameId;

        APIRequest bannerRequest = APIRequestInstance.getReq(TAG, reqUrl, null, new ResponseNetworkTask() {

            @Override
            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                respGame = apiResponse.getGame();
                if (TextUtils.isEmpty(respGame.getGameName()) || isFinishing()) {
                    return;
                }


                //                mImgIconGift.setVisibility(View.VISIBLE);
                mGameName.setText(respGame.getGameName());
                mTxtTitle.setText(respGame.getGameName());
                mGameTags.setText(respGame.getTypeText());
                mGameDldCnt.setText(" (" + String.format(getString(R.string.download_count), respGame.getDownloadNum() + "") + ")");
                //                mGameSize.setText(respGame.getSize());
                //                mGameDescription.setText(respGame.getIntroduce());
                mGameStars.setRating(NumberFormatUtils.getDivideResult(respGame.getStar()));


                Glide.with(ActGameDetails.this).load(respGame.getIconImage()).into(mGameIcon);

                Glide.with(ActGameDetails.this).load(respGame.getDetailBackImage()).into(mImgBg);


                mFragmentGameDetail.setData(respGame);


                setButtonStatue(selectType);
//                if (!bShowDownloadBtn) {
//                    mBtnDown.setVisibility(View.GONE);
//                    return;
//                }
//                mBtnDown.setVisibility(View.VISIBLE);
//                DownBtnUtils.addDownloadBtnListener(mBtnDown, ActGameDetails.this,
//                        mInstallButtonMgr, respGame, "game_detail" + respGame.getId());


//               mInstallButtonMgr.put(respGame.getDownloadUrl(),
//                        InstallButtonUtils.init("game_detail", respGame.getDownloadUrl(),
//                                mBtnDown, "game_detail"));
//
//                DownBtnUtils.addDownloadBtnListener(mBtnDown, ActGameDetails.this, mInstallButtonMgr, respGame, "game_detail");
//                GameStatusScanner scanner = new GameStatusScanner(ActGameDetails.this, mBtnDown, TAG) {
//                    @Override
//                    public void onButtonClickReturnListener(String downloadUrl, boolean bPaused, int percent) {
//                        mBtnDown.updateButtonUI(bPaused ? KFProgressButton.STATUS.STATUS_PAUSED : KFProgressButton.STATUS.STATUS_INSTALLING);
//                    }
//                };
//                scanner.compare(respGame);
//                scanner.addListener();


                if (respGame == null || TextUtils.isEmpty(respGame.getDownloadUrl())) {
                    mBtnDown.setEnabled(false);
                    mBtnDown.setText(getString(R.string.please_wait));
                    mBtnDown.setVisibility(View.VISIBLE);
                }
            }

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

            }

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

        KFZSNetwork.addRequest(bannerRequest);

    }


    /**
     * 安装按钮状态更新
     *
     * @param info
     */
    @Subscribe
    public void onEventMainThread(DownloadStatus info) {
        if (mOnDownCallback == null) {
            mOnDownCallback = DownBtnUtils.installBtnStatus(mInstallButtonMgr);
        }
        EventDownloadHandler.newInstance(this, mOnDownCallback)
                .setmTag(TAG).handlDownloadResult(info);
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        if (event.getEventTypes() == EventTypes.STORAGE_LOW) {
            DialogStorageLow.showDialog(this);
        }
    }


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

    /**
     * 获取借着完状态
     * return 401:未登录 400：未绑定手机 200：成功
     */
    public void loadLoanUserercord(final String sGameId) {
        String url = UrlBll.V2.BORROW_PLAY_LOAN_USERRECORD;
        HashMap<String, String> m = new HashMap<>();
        m.put("gameId", sGameId);
        APIRequestV2 apiRequestV2 = APIRequestInstance.getReqUrlV2(url,
                url, m, new Response.Listener<BaseMsg>() {
                    @Override
                    public void onResponse(BaseMsg baseMsg) {
//                        doNetworkTask(sGameId);
                        String s = baseMsg.getMsg();
                        int code = baseMsg.getCode();
                        switch (code) {
                            case 400:
//                                G.showToast("请绑定手机号");
                                return;
                            case 401:
//                                G.showToast(baseMsg.getMsg() + "");
                                return;
                            case 200:
                                UserRecord u = baseMsg.getData(UserRecord.class);
                                if (u != null) {
                                    userRecord = u;
                                }
                                break;
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                });
        KFZSNetwork.addRequest(apiRequestV2);
    }

    /**
     *
     */
    private boolean getFlagBorrow() {
        if (userRecord == null) {
            return false;
        }
        if (userRecord.getLoan_state() == 2 && userRecord.getHave_access_state() == 1) {
            return true;
        }
        return false;
    }

    @Download.onTaskStop void stopDownload(DownloadTask task){
        if(isThisGame(task)){
            mBtnDown.setText("暂停");
        }
    }
    @Download.onTaskStart void startDownload(DownloadTask task){
        if(isThisGame(task)){
            mBtnDown.setText("下载");
        }
    }

    @Download.onTaskComplete void completeDownload(DownloadTask task){
        if(isThisGame(task)){
            mBtnDown.setText("安装");
        }
    }

    @Download.onTaskRunning void runDownload(DownloadTask task){
        if(isThisGame(task)){
            mBtnDown.setText("下载中");
        }
    }
    private boolean isThisGame(DownloadTask task){
        return respGame != null && task != null && TextUtils.equals(task.getKey(), respGame.getDownloadUrl());
    }
}
