package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.AppCompatRatingBar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
import com.sheep.gamegroup.util.DownloadUtil;
import com.kfzs.duanduan.view.ViewPagerAutoHeigh;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.entity.PlayGameEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.fragment.FgtPlaGameGift;
import com.sheep.gamegroup.view.fragment.FgtPlayGameDetail;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

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

import java.util.Locale;

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

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

/**
 * Created by ljy on 2018/9/4.
 */

public class ActPlayGameDetail extends BaseActivity implements Action1<Integer> {
    @BindView(R.id.appbar_act_game_details)
    AppBarLayout appbarActGameDetails;
    @BindView(R.id.status_height_view)
    View statusHeightView;
    @BindView(R.id.find_game_bar)
    View find_game_bar;
    @BindView(R.id.title_bottom_line)
    LinearLayout title_bottom_line;
    @BindView(R.id.img_baseactivity_title)
    ImageView img_baseactivity_title;
    @BindView(R.id.txt_baseactivity_title)
    TextView txt_baseactivity_title;
    @BindView(R.id.ibtn_baseactivity_right)
    ImageButton ibtn_baseactivity_right;
    @BindView(R.id.find_game_iv)
    ImageView find_game_iv;
    @BindView(R.id.find_game_name_tv)
    TextView find_game_name_tv;
    @BindView(R.id.find_game_info_tv)
    TextView find_game_info_tv;
    @BindView(R.id.find_game_xin)
    AppCompatRatingBar find_game_xin;
    @BindView(R.id.find_game_down_tv)
    TextView find_game_down_tv;
    @BindView(R.id.viewpager_act_game_details)
    ViewPagerAutoHeigh mViewPager;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.welfare_gift_layout)
    LinearLayout welfare_gift_layout;
    @BindView(R.id.welfare_tv)
    TextView welfare_tv;
    @BindView(R.id.gift_tv)
    TextView gift_tv;
    @BindView(R.id.ll_game_tag)
    LinearLayout ll_game_tag;

    private Activity activity;
    private int id;
    private boolean mIsExpanded = false;//是否是折叠状态

    private GameEntity gameEntity;
    private PlayGameEntity playGameEntity;
    private boolean isNeedReservation = false;

    private TitleFragmentListAdapter mAdapter;
    private int curPosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.act_play_game_detail_layout;
    }

    @Override
    public void initView() {
        id = getIntent().getIntExtra("id", 0);
        activity = this;
        TitleBarUtils.getInstance()
                .setTitle(this, "详情")
                .setTitleFinish(this);
        EventBus.getDefault().register(this);
        Aria.download(this).register();

        mAdapter = new TitleFragmentListAdapter(getSupportFragmentManager());
        txt_baseactivity_title.setVisibility(View.INVISIBLE);//不显示标题栏

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 0);
        statusHeightView.setLayoutParams(params);

        appbarActGameDetails.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int nameWidth = find_game_name_tv.getWidth();
                if (nameWidth == 0) {
                    find_game_name_tv.measure(0, 0);
                    nameWidth = find_game_name_tv.getMeasuredWidth();
                }
                int infoWidth = find_game_info_tv.getWidth();
                if (infoWidth == 0) {
                    find_game_info_tv.measure(0, 0);
                    infoWidth = find_game_info_tv.getMeasuredWidth();
                }
                //图标位置变化
                int find_game_top = getResources().getDimensionPixelSize(R.dimen.find_game_top);
                int find_icon_with = getResources().getDimensionPixelSize(R.dimen.find_icon_with);
//                int leftMargin = getResources().getDimensionPixelSize(R.dimen.content_padding_5);
                int titleHeight = img_baseactivity_title.getHeight();
                int titleWidth = img_baseactivity_title.getWidth();
                int topRow = (titleHeight - find_game_name_tv.getHeight() - find_game_info_tv.getHeight()) / 5;
                int topRow2 = (titleHeight - find_game_name_tv.getHeight()) / 2;
                int leftRow = topRow2 / 4;//isNeedReservation ? topRow : 5 * topRow;

                int willTop = Math.max(topRow/2, find_game_top + verticalOffset);
                int row = (find_icon_with * willTop + titleHeight * (find_game_top - willTop)) / find_game_top - topRow;
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) find_game_iv.getLayoutParams();
                layoutParams.leftMargin = Math.max(titleWidth, (G.WIDTH - find_icon_with) / 2 + verticalOffset);
                layoutParams.topMargin = willTop;
                layoutParams.width = row;
                layoutParams.height = row;
                find_game_iv.setLayoutParams(layoutParams);
                //名字位置变化
                RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) find_game_name_tv.getLayoutParams();
                layoutParams2.leftMargin = Math.max(titleWidth + row + 2 * leftRow, (G.WIDTH - nameWidth) / 2 + verticalOffset);
                layoutParams2.topMargin = Math.max(topRow2, getResources().getDimensionPixelSize(R.dimen.find_game_top2) + verticalOffset);
                find_game_name_tv.setLayoutParams(layoutParams2);
                //tag
                RelativeLayout.LayoutParams layoutParams6 = (RelativeLayout.LayoutParams) ll_game_tag.getLayoutParams();
                layoutParams6.topMargin = getResources().getDimensionPixelSize(R.dimen.find_game_top165) + verticalOffset;
                ll_game_tag.setLayoutParams(layoutParams6);
                //信息位置变化
                RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) find_game_info_tv.getLayoutParams();
                int left1 = (G.WIDTH - infoWidth) / 2;
                int left2 = titleWidth + row + 2 * leftRow;
                layoutParams3.leftMargin = left1;//left2 > left1 ? Math.min(left2, left1 - verticalOffset) : Math.max(left2, left1 + verticalOffset);
                layoutParams3.topMargin = /*Math.max(find_game_name_tv.getHeight() + 4 * topRow, */getResources().getDimensionPixelSize(R.dimen.find_game_top190) + verticalOffset/*)*/;
                find_game_info_tv.setLayoutParams(layoutParams3);
                //下载按钮位置变化
                RelativeLayout.LayoutParams layoutParams4 = (RelativeLayout.LayoutParams) welfare_gift_layout.getLayoutParams();
                layoutParams4.setMarginEnd(Math.max(ibtn_baseactivity_right.getWidth(), (G.WIDTH - welfare_gift_layout.getWidth()) / 2 + verticalOffset));
                layoutParams4.topMargin = getResources().getDimensionPixelSize(R.dimen.find_game_top5) + verticalOffset;//Math.max((titleHeight - welfare_gift_layout.getHeight()) / 2, getResources().getDimensionPixelSize(R.dimen.find_game_top4) + verticalOffset);// Math.max(topRow, getResources().getDimensionPixelSize(R.dimen.find_game_top4) + verticalOffset);
                welfare_gift_layout.setLayoutParams(layoutParams4);
                //星级位置变化
                RelativeLayout.LayoutParams layoutParams5 = (RelativeLayout.LayoutParams) find_game_xin.getLayoutParams();
                layoutParams5.topMargin = getResources().getDimensionPixelSize(R.dimen.find_game_top210) + verticalOffset;
                if (willTop == topRow/2) {
                    if (mIsExpanded) {
//                        txt_baseactivity_title.setVisibility(View.INVISIBLE);
                        find_game_bar.setVisibility(View.VISIBLE);
                        title_bottom_line.setVisibility(View.VISIBLE);
                        img_baseactivity_title.setImageLevel(1);
                        mIsExpanded = false;//修改状态标记为折叠
                    }
                } else {
                    if (!mIsExpanded) {
                        mIsExpanded = true;//修改状态标记为展开
//                        txt_baseactivity_title.setVisibility(View.VISIBLE);
                        find_game_bar.setVisibility(View.INVISIBLE);
                        title_bottom_line.setVisibility(View.INVISIBLE);
                        img_baseactivity_title.setImageLevel(0);
                    }
                }
            }
        });

        resetData();

    }

    private void resetData() {
        //游戏简介与下载
        ViewUtil.setText(find_game_name_tv);
        ViewUtil.setText(find_game_info_tv);
        ViewUtil.setText(find_game_down_tv);
        find_game_xin.setRating(0.0f);
        //游戏介绍
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        GameEntity gameEntity = DataUtil.getInstance().getCacheResult(ApiKey.applications(id), GameEntity.class);
        loadApp(gameEntity);

        initDetailFromNet();
    }

    private void loadApp(GameEntity gameEntity) {
        if (gameEntity != null) {
            loadData(gameEntity);
        } else {
            resetData();
        }
    }

    private void loadData(GameEntity gameEntity) {
        this.gameEntity = gameEntity;
        playGameEntity = gameEntity.getApp();
        if(gameEntity == null ||playGameEntity == null){
            return;
        }
        //游戏简介与下载
        GlideImageLoader.setGameImage(find_game_iv, gameEntity.getApp().getIcon()+"");
        ViewUtil.setText(find_game_name_tv, gameEntity.getApp().getName());
        isNeedReservation = !gameEntity.getApp().isCanDownload();//这里认为只有两种状态：可下载与预约下载
//        if (isNeedReservation)
//            ViewUtil.setText(find_game_info_tv, String.format(Locale.CHINA, "开放时间：%s", TimeUtil.TimeStamp2Date(gameEntity.getApp().getDownload_at(), "yyyy-MM-dd\u0020HH:mm")));
//        else {
//            String format = "包体大小 (%sM)";
//            ViewUtil.setText(find_game_info_tv, String.format(Locale.CHINA, format, gameEntity.getApp().getPackage_size()));
//        }
        String format = "包体大小 (%sM)";
        ViewUtil.setText(find_game_info_tv, String.format(Locale.CHINA, format, gameEntity.getApp().getPackage_size()));

        find_game_xin.setRating(gameEntity.getApp().getScore() / 2);

        updateView(this, gameEntity.getApp(), find_game_down_tv);

        mAdapter.clearData();
        mAdapter.add(FgtPlayGameDetail.newInstance(gameEntity), "详情");
        //ViewPager
        //welfare_gift_layout
        if(gameEntity.isGiftAndBonus()){
            welfare_gift_layout.setVisibility(View.GONE);
        }else {
            welfare_gift_layout.setVisibility(View.VISIBLE);
            mAdapter.add(FgtPlaGameGift.newInstance(gameEntity), "礼包");
            if(gameEntity.isGift()){
                gift_tv.setVisibility(View.VISIBLE);
            }else {
                gift_tv.setVisibility(View.GONE);
            }
            if(TextUtils.isEmpty(gameEntity.getBonusText())){
                welfare_tv.setVisibility(View.GONE);
            }else {
                welfare_tv.setVisibility(View.VISIBLE);
                ViewUtil.setText(welfare_tv, String.format(Locale.CHINA, "+%s元", gameEntity.getBonusText()));
            }
        }

        mViewPager.setAdapter(mAdapter);
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
        tabLayout.setupWithViewPager(mViewPager);
        CommonUtil.getInstance().reflex(tabLayout, activity);

        //tag 标签绘制
        CommonUtil.getInstance().paintLineaLayout(activity, gameEntity, ll_game_tag, 4,R.color.txt_bule, R.drawable.shape_blue_stroke_rectangle_no_lb);

    }

    //更新按钮状态与添加点击事件
    private void updateView(final Activity activity, PlayGameEntity playGameEntity, TextView textView) {

        CommonUtil.getInstance().palyGameDetailBtnValue(activity,gameEntity,textView, 0);
    }


    private void initDetailFromNet() {
        showProgress();
        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);
                            loadApp(gameEntity);
                        }
                        hideProgress();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        resetData();
                        hideProgress();
                    }
                });
    }
    @Override
    public void call(Integer integer) {

    }

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

    //下载状态监听

    @Download.onPre
    void onPre(DownloadTask task) {
        if(TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }

        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText("准备下载中");
        }
    }

    @Download.onTaskStart
    void taskStart(DownloadTask task) {
        if(TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText("开始下载中");
        }
    }

    @Download.onTaskResume
    void taskResume(DownloadTask task) {
        if(TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText("恢复下载中");
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        if(gameEntity == null || TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText(String.format(Locale.CHINA, "%d%%", Math.abs(task.getPercent())));
        }
    }

    @Download.onTaskStop
    void taskStop(DownloadTask task) {
        if(gameEntity == null || TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

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

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {
        if(gameEntity == null || TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText("已经取消");
        }
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        if(gameEntity == null || TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        if(gameEntity == null || TextUtils.isEmpty(gameEntity.downLinks())) {//游戏任务
            return;
        }
        if (find_game_down_tv != null && gameEntity.downLinks().equals(task.getKey())) {
            find_game_down_tv.setText(CommonUtil.START_INSTALL);
        }
        if (gameEntity != null && gameEntity.getApp() != null && TextUtils.equals(task.getKey(), gameEntity.getApp().getDownload_link()))
            gameEntity.getApp().updateState(DownloadUtil.STATUS_FINISH);
        if (gameEntity != null && gameEntity.getRelease_task() != null && TextUtils.equals(task.getKey(), gameEntity.getApp().getDownload_link()))
            gameEntity.getRelease_task().getDownloadHelper().updateState(DownloadUtil.STATUS_FINISH);
    }

    @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:", "");
            if (playGameEntity == null || !TextUtils.equals(packageName, playGameEntity.getPackage_names())) {
                return;
            }

            if (find_game_down_tv != null) {
                switch (intent.getAction()) {
                    case ACTION_PACKAGE_ADDED:
                        find_game_down_tv.setText(CommonUtil.GAME_OPEN);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName, playGameEntity.getDownload_url());
                        if (TextUtils.isEmpty(path)) {
                            find_game_down_tv.setText(CommonUtil.START_DOWNLOAD);
                        } else {
                            find_game_down_tv.setText(CommonUtil.START_INSTALL);
                        }
                        break;
                }
            }

            if (TextUtils.equals(packageName, playGameEntity.getPackage_names())) {
                switch (intent.getAction()) {
                    case ACTION_PACKAGE_ADDED:
                        if(playGameEntity != null)
                            playGameEntity.updateState(DownloadUtil.STATUS_INSTALLED);
                        if(gameEntity.getRelease_task() != null)
                            gameEntity.getRelease_task().getDownloadHelper().updateState(DownloadUtil.STATUS_INSTALLED);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName, playGameEntity.getDownload_url());
                        if (TextUtils.isEmpty(path)) {
                            if(playGameEntity != null)
                                playGameEntity.updateState(DownloadUtil.STATUS_INIT);
                            if(gameEntity.getRelease_task() != null)
                                gameEntity.getRelease_task().getDownloadHelper().updateState(DownloadUtil.STATUS_INIT);
                        } else {
                            if(playGameEntity != null)
                                playGameEntity.updateState(DownloadUtil.STATUS_FINISH);
                            if(gameEntity.getRelease_task() != null)
                                gameEntity.getRelease_task().getDownloadHelper().updateState(DownloadUtil.STATUS_FINISH);
                        }
                        break;
                }
            }
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()){
            case REFRESH_XIAOMI_GAME_LIST:
                initData();
                break;
        }
    }
}
