package com.wasu.cs.ui;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wasu.cs.model.NewFilmSpecialData;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.RecyclerPauseOnScrollListener;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.log.WLog;
import com.wasu.util.StringUtils;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapterTv;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolderTv;
import com.wasu.widgets.focuswidget.IRecyclerView;
import com.wasu.widgets.focuswidget.TvRecyclerView;

import org.json.JSONObject;

import java.util.List;

import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * @author jeepc
 * @ClassName: ActivityNewFilmSpecial
 * @Description: 新版影视剧专题
 */
public class ActivityNewFilmSpecial extends ActivityBase {
    private String TAG = "ActivityNewFilmSpecial";
    private ImageView bg_iv;
    private TvRecyclerView mContent_rc;

    private NewFilmSpecialData mData;
    private String jsonUrl = null;

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG, "doCreate()");

        setContentView(R.layout.activity_new_film_special);
        jsonUrl = getIntent().getStringExtra(IntentConstant.DATAURI.value());
        bg_iv = (ImageView) findViewById(R.id.bg_iv);
        mContent_rc = (TvRecyclerView) findViewById(R.id.content_rc);
        mContent_rc.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
//                outRect.left = getResources().getDimensionPixelSize(com.wasu.module.wechattv.R.dimen.d_16dp);
                outRect.left = getResources().getDimensionPixelSize(R.dimen.d_30dp);
                //outRect.top = getResources().getDimensionPixelSize(R.dimen.d_8dp);

            }
        });
        mContent_rc.addOnScrollListener(new RecyclerPauseOnScrollListener(true, true));
        initData();
    }

    /**
     * @param
     * @return void
     * @throws
     * @author 海迪
     * @Title: reqLabelAreaData
     * @Description: 向后台请求数据， 成功后，初始化Activity
     */
    private void initData() {

        if (jsonUrl == null || StringUtils.isBlank(jsonUrl)) {
            finish();
        } else {
            jsonUrl = jsonUrl.trim() + "&page=1&psize=200";
        }

        showLoading();
        DataFetchModule.getInstance().fetchJsonGet(jsonUrl, new DataFetchListener.JsonListener() {
            @Override
            public void onJsonGet(int retcode, String extraMsg, JSONObject jsondata) {
                hideLoading();
                if (retcode == 0) {
                    Gson gson = new Gson();
                    mData = gson.fromJson(jsondata.toString(), NewFilmSpecialData.class);
                    if (mData != null && mData.getData() != null && mData.getData().getBody() != null) {
                        init();
                    }
                } else {
                    showErrorExitDlg(ErrorMap.mapError(ActivityNewFilmSpecial.this, retcode, extraMsg));
                }
            }
        });
//		String url = "http://121.40.195.74/?s=2005&p=sntAssetList&k=1&v=1&catId=280571&eid=149&ecatId=276043&page=1&psize=100";
    }

    private void init() {
        //设置背景
        if (mData.getData().getDetail() != null) {
            String bgUrl = mData.getData().getDetail().getBgPicUrl();
            FrescoImageFetcherModule.getInstance().attachImage(bgUrl,bg_iv);
        }
        //设置recyclerview
        final List<NewFilmSpecialData.DataBean.BodyBean.ListBean> list = mData.getData().getBody().getList();
        if (list != null && list.size() > 0) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(ActivityNewFilmSpecial.this, LinearLayoutManager.HORIZONTAL, false);
            mContent_rc.setLayoutManager(layoutManager);
            MyAdapter adapter = new MyAdapter(mContent_rc);
            adapter.setData(list);
            adapter.setOnItemListener(new BaseFocusRecyclerViewAdapterTv.OnItemListener() {
                @Override
                public void onItemClick(IRecyclerView parent, View itemView, int position) {
                    position = position%list.size();
                    IntentMap.startIntent(ActivityNewFilmSpecial.this, null, list.get(position).getLayout(),
                            list.get(position).getJsonUrl(), null);
                }

                @Override
                public void onItemFocusChanged(IRecyclerView parent, View itemView, int position, boolean hasFocus) {

                }
            });
            mContent_rc.setAdapter(adapter);
            int pos = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % list.size();
            mContent_rc.getLayoutManager().scrollToPosition(pos);
            setItemFocus(pos);
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                setItemFocus(tempIndex);
            }
        }
    };

    int tempIndex = -1;

    private void setItemFocus(int index) {
        tempIndex = index;
        View view = mContent_rc.getLayoutManager().findViewByPosition(index);
        if (view == null) {
            handler.sendEmptyMessageDelayed(0, 100);
        } else {
            view.requestFocus();
        }
    }

    class MyAdapter extends BaseFocusRecyclerViewAdapterTv<NewFilmSpecialData.DataBean.BodyBean.ListBean> {
        private int mCount = 0;


        public MyAdapter(TvRecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        public NewFilmSpecialData.DataBean.BodyBean.ListBean getItemData(int position) {
            return super.getItemData(position % mCount);
        }

        @Override
        public void setData(List<NewFilmSpecialData.DataBean.BodyBean.ListBean> data) {
            mCount = data.size();
            super.setData(data);
        }

        @Override
        public int getItemCount() {
            return Integer.MAX_VALUE;//用于循环
        }

        @Override
        protected BaseFocusRecyclerViewHolderTv createItem(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(ActivityNewFilmSpecial.this).inflate(R.layout.item_new_film_special, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        protected void bindData(final BaseFocusRecyclerViewHolderTv holder, final int position) {
            NewFilmSpecialData.DataBean.BodyBean.ListBean data = getItemData(position);
            FrescoImageFetcherModule.getInstance().attachImage(data.getPicUrl(), ((MyViewHolder) holder).pic);
            ((MyViewHolder) holder).name.setText(data.getTitle());
        }

        class MyViewHolder extends BaseFocusRecyclerViewHolderTv {

            public View view;
            public ImageView pic;
            public TextView name;

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView item View
             */
            public MyViewHolder(View itemView) {
                super(itemView, getItemParent(), getItemListener());
                view = itemView;
                pic = (ImageView) itemView.findViewById(R.id.pic);
                name = (TextView) itemView.findViewById(R.id.name);
            }

            @Override
            protected View getView() {
                return view;
            }
        }
    }

}

