package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONArray;
import com.kfzs.duanduan.ActDownloadMgr;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GridViewEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.adapter.AdpTryMakemoney;
import com.sheep.gamegroup.view.adapter.AdpTrymakemoneyTabGridview;
import com.sheep.gamegroup.view.fragment.FgtTryMakeMoney;
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.TitleBarUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 试着赚钱页面
 * Created by ljy on 2018/3/10.
 */

public class TryMakeMoneyact extends BaseActivity {
    @BindView(R.id.indicator)
    TabLayout indicator;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.tab_gridview)
    MyGridview tabGridview;
    @BindView(R.id.select_tab_iv)
    ImageView selectTabIv;
    @BindView(R.id.task_gridview_layout)
    LinearLayout task_gridview_layout;
    private Activity activity;

    private AdpTryMakemoney mAdapter;
    private String[] titles = new String[]{"推荐任务", "即将开始"};

    private AdpTrymakemoneyTabGridview tabGridviewAdp;
    private ArrayList<Object> gridviewListAll = new ArrayList<>();
    private ArrayList<Object> gridviewList = new ArrayList<>();
    private boolean clickFlag = false;
    private GridViewEntity gridViewEntity;//选中的
    private int select;

    private int is_succession;//0:一般任务 1:连续任务

    private String title;

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

    @Override
    public void initView() {
        activity = this;
        is_succession = getIntent()
                .getIntExtra(
                        "is_succession", 0);
        if(is_succession == 1){
            title = "连续任务";
        }else {
            title = "试玩赚钱";
        }
        TitleBarUtils
                .getInstance()
                .setTitle(activity, title).setTitleFinish(activity)
                .setRightImgBotton(activity, R.drawable.index_download, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(TryMakeMoneyact.this, ActDownloadMgr.class));
                        UMConfigUtils.onEvent(UMConfigUtils.Event.GAME_DOWNLOAD_MANAGER);
                    }
                });

        mAdapter = new AdpTryMakemoney(getSupportFragmentManager(), this);
        mAdapter.add(FgtTryMakeMoney.newInstance(0), titles[0]);
        mAdapter.add(FgtTryMakeMoney.newInstance(2), titles[1]);
        pager.setAdapter(mAdapter);
        indicator.setupWithViewPager(pager);

        tabGridviewAdp = new AdpTrymakemoneyTabGridview(activity, gridviewList);
        tabGridview.setAdapter(tabGridviewAdp);
    }

    @Override
    public void initListener() {
        tabGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(gridViewEntity == (GridViewEntity) gridviewList.get(position)){
                    return;
                }
                select = position;
                gridViewEntity = (GridViewEntity) gridviewList.get(position);
                for(int i=0;i<gridviewList.size();i++){
                    if(position == i){
                        ((GridViewEntity) gridviewList.get(i)).setSelectState(true);
                    }else {
                        ((GridViewEntity) gridviewList.get(i)).setSelectState(false);

                    }
                    tabGridviewAdp.notifyDataSetChanged();
                }
                try{
                    //刷新界面
                    mAdapter.getItem(indicator.getSelectedTabPosition()).onResume();
                    Log.e("-----select position",indicator.getSelectedTabPosition()+"");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void initData() {
        if(is_succession == 0){
            SheepApp.get(activity)
                    .getNetComponent()
                    .getApiService()
                    .getChildTask(1)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                        @Override
                        public void onError(BaseMessage baseMessage) {
                            G.showToast(baseMessage.getMsg()+"");
                            task_gridview_layout.setVisibility(View.GONE);
                        }

                        @Override
                        public void onNext(BaseMessage baseMessage) {

                            task_gridview_layout.setVisibility(View.VISIBLE);
                            List<GridViewEntity> entityList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), GridViewEntity.class);
                            if(entityList != null){
                                gridviewListAll.clear();
                                gridviewListAll.add(new GridViewEntity(true, -1, "全部" ));
                                gridviewListAll.addAll(entityList);
                                setValueList2(clickFlag);
                            }
                        }
                    });
        }else {
            task_gridview_layout.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.select_tab_iv)
    public void onViewClicked() {
        clickFlag = !clickFlag;
        setValueList2(clickFlag);
        tabGridviewAdp.notifyDataSetChanged();
    }

    /**
     * 获取tab的值，fragment调用
     */
    public GridViewEntity getTabValue(){
        return gridViewEntity;
    }

    /**
     * 获取is_succession，是否是连续任务
     */
    public int getIsSuccession(){
        return is_succession;
    }


    /**
     * test
     * list 赋值
     */
    private void setValueList() {
        gridviewListAll.clear();
        for (int i = 0; i < 10; i++) {
            if(i == 0){
                gridviewListAll.add(new GridViewEntity(true, "click_" + i));
            }else {
                gridviewListAll.add(new GridViewEntity(false, "click_" + i));
            }

        }
        setValueList2(clickFlag);
    }
    private void setValueList2(boolean flag) {
        gridviewList.clear();
        if(flag || gridviewListAll.size() <= 4){
            gridviewList.addAll(gridviewListAll);
            selectTabIv.setRotation(180);
        }else {
            selectTabIv.setRotation(0);
            for (int i = 0; i < 4; i++) {
                gridviewList.add(gridviewListAll.get(i));
            }
        }
        tabGridviewAdp.notifyDataSetChanged();
    }
}
