package com.wasu.cs.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wasu.cs.adapter.BaseRecyclerViewAdapter;
import com.wasu.cs.adapter.ImageAdapter;
import com.wasu.cs.adapter.RowRecyclerViewAdapter;
import com.wasu.cs.model.CatData;
import com.wasu.cs.model.DemandList;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.widget.BlockLinearLayout;
import com.wasu.cs.widget.CircleFlowIndicator;
import com.wasu.cs.widget.ListScrollView;
import com.wasu.cs.widget.RowRecyclerView;
import com.wasu.cs.widget.ViewFlow;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;

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

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

/**
 * 中国蓝TV CS模板
 * Created by Danxingxi on 2016/6/6.
 */
public class ActivityCNLTVCSModel extends ActivityBase implements View.OnClickListener {
    private static final String TAG = "ActivityCNLTVCSModel";
    private String csJsonUrl;
    private CatData catData = new CatData();//cs模板栏目数据
    private CatProtocol catProtocol;
    private ListScrollView listScrollView;
    private MyAdapter mAdapter;
    private ViewFlow viewFlow;
    private BlockLinearLayout focusSearchLayout;
    private LinearLayout headerFocusLayout;//头部焦点控件
    private List<CatData.AssetElement> headerData = new ArrayList<CatData.AssetElement>();//中国蓝广告数据
    private SparseArray<String> listColumeLogo = new SparseArray<>();//行数据栏目logo
    private SparseArray<DemandList> rowDatas = new SparseArray<>();//所有行数据
    private RowRecyclerView firstRowRecyclerView;
    //private SparseArray<String> listColumeLogo=new SparseArray<String>();//行数据栏目logo
    //private SparseArray<List<CatData.AssetElement>> rowDatas = new SparseArray<List<CatData.AssetElement>>();//所有行数据

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

        setContentView(R.layout.activity_cnltv_csmodel);
        csJsonUrl = getIntent().getStringExtra(IntentConstant.DATAURI.value());
        listScrollView = (ListScrollView) findViewById(R.id.listScrollView);
        focusSearchLayout = (BlockLinearLayout) findViewById(R.id.layoutBody);
        focusSearchLayout.setOnFocusSearchListener(focusSearchListener);
        headerFocusLayout = (LinearLayout) findViewById(R.id.headerFocusLayout);
        headerFocusLayout.setOnClickListener(this);
        headerFocusLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (null != firstRowRecyclerView) {
                        if (firstRowRecyclerView.getChildAt(0) != null) {
                            firstRowRecyclerView.getChildAt(0).requestFocus();
                            return true;
                        }
                        return true;
                    } else {
                        return true;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (null != viewFlow) {
                        viewFlow.setSelection(viewFlow.getSelectedItemPosition() - 1);
                    }
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (null != viewFlow) {
                        viewFlow.setSelection(viewFlow.getSelectedItemPosition() + 1);
                    }
                    return true;
                }
                return false;
            }
        });

        initData();
    }

    @Override
    protected void setDefaultBg(Drawable drawable) {
//        super.setDefaultBg(drawable);
        getWindow().setBackgroundDrawableResource(R.color.black_alpha_08);
    }

    private void initData() {
        catProtocol = new CatProtocol();
        catProtocol.fetchData(new Handler(), csJsonUrl, new CatProtocol.CatFetchCallback() {
            @Override
            public void onResult(boolean successed, CatData data) {
                if (successed && null != data && data.getAssets().size() > 0) {
                    catData = data;
                    fetchHeaderData();
                    fetchRowData();
                } else {
                    showErrorExitDlg("数据获取失败，请重试！");
                }
            }
        });
    }

    /**
     * 初始化header的轮播广告
     **/
    private void fetchHeaderData() {
        String headerUrl;
        if (catData.getAssets().get(0).getTitle().equals("banner")) {
            headerUrl = catData.getAssets().get(0).getCsJsonUrl();
            if (!TextUtils.isEmpty(headerUrl)) {
                catProtocol.fetchData(new Handler(), headerUrl, new CatProtocol.CatFetchCallback() {
                    @Override
                    public void onResult(boolean successed, CatData catData) {
                        if (successed && catData != null && catData.getAssets().size() > 0) {
                            headerData = catData.getAssets();
                            initHeaderView();
                        } else {
                            WLog.e(TAG, "header data fetch error!");
                        }
                    }
                });
            }
        }

    }

    /**
     * 获取body的所有行数据
     **/
    private void fetchRowData() {
        catData.getAssets().remove(0);//移除第0个banner数据
        final int size = catData.getAssets().size();
        /**循环获取每一行的数据**/
        for (int i = 0; i < size; i++) {
            final int pos = i;

           /* DataFetchModule.getInstance().fetchJsonGet(catData.getAssets().get(i).getCsJsonUrl(), new DataFetchListener.JsonListener() {
                @Override
                public void onJsonGet(int retcode, String extraMsg, JSONObject jsondata) {
                    if (retcode != 0) {
                        return;
                    }
                    CatData data = new CatData();
                    data.from(jsondata);
                    if (data.getAssets().size() > 0) {
                        rowDatas.put(pos, data.getAssets());
                        listColumeLogo.put(pos, data.getCat().getBgImage());//获取行数据栏目logo
                        if (rowDatas.size() == size) {
                            initBodyView();
                        }
                    }
                }
            });*/
            DataFetchModule.getInstance().fetchObjectGet(catData.getAssets().get(i).getCsJsonUrl(),DemandList.class,
                    new DataFetchListener.ObjectListener() {
                @Override
                public void onObjectGet(int retcode, String s, ObjectBase object) {
                    if (retcode != 0) {
                        return;
                    }
                    DemandList demandList = (DemandList) object;
                    if(demandList!=null&&demandList.getDatum()!=null&&demandList.getDatum().getAssets()!=null&&demandList.getDatum().getAssets().size()>0){
                        rowDatas.put(pos, demandList);
                        listColumeLogo.put(pos, demandList.getDatum().getBgImage());//获取行数据栏目logo
                        if (rowDatas.size() == size) {
                            initBodyView();
                        }
                    }
                }
            });
        }
    }

    /**
     * 显示header轮播海报图
     */
    private void initHeaderView() {
        viewFlow = (ViewFlow) findViewById(R.id.viewFlow);
        viewFlow.setAdapter(new ImageAdapter(ActivityCNLTVCSModel.this, headerData));
        viewFlow.setmSideBuffer(headerData.size()); // 设置图片5张
        viewFlow.setTimeSpan(5000);
        CircleFlowIndicator indic = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
        viewFlow.setFlowIndicator(indic);
        viewFlow.setSelection(0);           // 设置初始位置
        if (headerData.size() > 1) {
            viewFlow.startAutoFlowTimer(); // 启动自动播放
        }
    }

    /**
     * 数据请求完了后显示body UI
     */
    private void initBodyView() {
        /**需要先创建适配器后才能设置适配器，因为一设置适配器就会去显示数据**/
        mAdapter = new MyAdapter(catData);
        /**设置适配器**/
        listScrollView.setAdapter(mAdapter);
    }

    /**
     * 焦点分发拦截控制
     */
    private final BlockLinearLayout.OnFocusSearchListener focusSearchListener = new BlockLinearLayout.OnFocusSearchListener() {
        @Override
        public View onFocusSearch(View focused, int direction) {
            if (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT) {
                return focused;
            }
            return null;
        }
    };

    /**
     * header控件跳转事件监听
     * author chenming
     * time 2016/06/30
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int adapterindex = -1;

        //加入判断，避免除数为0导致异常
        if (headerData != null && headerData.size() > 0 && viewFlow.getSelectedItemPosition() > 0) {
            adapterindex = viewFlow.getSelectedItemPosition() % headerData.size();
        } else {
            return;
        }

        String adcsjsonurl = headerData.get(adapterindex).getJsonUrl();
        String adcslayout = headerData.get(adapterindex).getLayout();
        IntentMap.startIntent(this, null, adcslayout, adcsjsonurl, null);

    }


    /**
     * 实现自定义的适配器
     */
    class MyAdapter extends ListScrollView.Adapter {
        CatData mCatData;

        //SparseArray<RowRecyclerView> mRowRecyclerViews = new SparseArray<>();

        public MyAdapter(CatData catData) {
            this.mCatData = catData;
            //WLog.d(TAG, "data size-->" + data.size());
        }

        @Override
        public View getView(ListScrollView parent, final int pos) {
            View view = LayoutInflater.from(ActivityCNLTVCSModel.this).inflate(R.layout.item_row_layout, null);
            TextView tvName = (TextView) view.findViewById(R.id.rowName);
            ImageView columeLogo = (ImageView) view.findViewById(R.id.columnlogo);
            tvName.setText(mCatData.getAssets().get(pos).getTitle());
            FrescoImageFetcherModule.getInstance().attachImage(listColumeLogo.get(pos), columeLogo);
            RowRecyclerView rowListView = (RowRecyclerView) view.findViewById(R.id.rowList);
            RowRecyclerViewAdapter adapter = new RowRecyclerViewAdapter(ActivityCNLTVCSModel.this, rowDatas.get(pos).getDatum().getAssets());
            adapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, Object data) {

                    DemandList demandList = rowDatas.get(pos);
                    demandList.getDatum().setTotal(demandList.getRealSize());

                    Intent intent = new Intent();
                    intent.putExtra(IntentConstant.PLAY_TYPE.value(), ActivityPlayer.PLAY_TYPE_LOOP);
                    intent.putExtra(IntentConstant.PLAY_INDEX.value(), position);
                    intent.putExtra(ActivityPlayer.ASSET_LIST, (Serializable) demandList);
                    rowDatas.get(pos).getSize();
                    IntentMap.startIntent(ActivityCNLTVCSModel.this, intent, null, null, ActivityPlayer.class);
                }
            });
            //设置布局管理器
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ActivityCNLTVCSModel.this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            rowListView.setHasFixedSize(true);
            rowListView.setLayoutManager(linearLayoutManager);
            rowListView.setAdapter(adapter);
            if (0 == pos) {
                firstRowRecyclerView = rowListView;
            }
            return view;
        }

        @Override
        public int getCount() {
            return mCatData.getAssets().size();
        }
    }

    @Override
    protected void onDestroy() {
        /**当退出时，停止广告轮播**/
        if (null != viewFlow) {
            viewFlow.stopAutoFlowTimer();
            viewFlow = null;
        }
        super.onDestroy();
        if (headerData != null) {
            headerData.clear();
            headerData = null;
        }
        if (rowDatas != null) {
            rowDatas.clear();
            rowDatas = null;
        }
        if (catProtocol != null) {
            catProtocol.cleanData();
            catProtocol = null;
        }


    }
}
