package com.wasu.cs.ui;

import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.cs.mvp.IView.ILifeMvpView;
import com.wasu.cs.mvp.model.AssetsDataModel;
import com.wasu.cs.mvp.presenter.MainLifePagePresenter;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.statistics.WasuStatistics;
import com.wasu.widgets.focuswidget.FocusRelativeLayout;

import java.util.List;

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

/**
 * @Description: 首页生活屏
 * @Author: Danxingxi
 * @CreateDate: 2016/11/30 10:20
 */
public class MainLifePageView extends FrameLayout implements View.OnClickListener, ILifeMvpView {

    private final static String TAG = MainLifePageView.class.getSimpleName();

    private SimpleDraweeView row11,row12,row13,row14,row15,row21,row22,row23,row24,row25,row26;
    private FocusRelativeLayout focusRelativeLayout;
    private String liveUrl;
    private Context mContext;
    private final static int LEFT_PAGE = 2;
    private final static int RIGHT_PAGE = 0;
    private final static String PageName = "生活";
    private String url = "http://120.26.137.228/?s=2002&p=sjctBlockList&k=1&v=4&type=0&subjectId=69&indCatId=245546";
    private ViewPager viewPager;
    private final static int MSG_RecycleImageView = 1;
    private final static int MSG_ShowImageView = 2;
    /**是否是第一次加载**/
    private boolean isFirst = true;
    /**imageView是否已经回收**/
    private boolean isRecycled = true;
    private MainLifePagePresenter mainLifePagePresenter;

    public MainLifePageView(Context context, String r, ViewPager pager) {
        super(context);
        if(!TextUtils.isEmpty(r)){
            url = r;
        }
        if(pager!=null){
            viewPager = pager;
        }
        init(context);
    }

    public MainLifePageView(Context context) {
        super(context);
        init(context);
    }

    public MainLifePageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MainLifePageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.main_life_pageview, this);
        initView();
        mainLifePagePresenter = new MainLifePagePresenter();
        mainLifePagePresenter.attachView(this);
        mainLifePagePresenter.getLifePageData(url);
    }

    private void initView(){
        focusRelativeLayout = (FocusRelativeLayout) findViewById(R.id.focusRelativeLayout);
        row11 = (SimpleDraweeView) findViewById(R.id.row11);
        row12 = (SimpleDraweeView) findViewById(R.id.row12);
        row13 = (SimpleDraweeView) findViewById(R.id.row13);
        row14 = (SimpleDraweeView) findViewById(R.id.row14);
        row15 = (SimpleDraweeView) findViewById(R.id.row15);
        row21 = (SimpleDraweeView) findViewById(R.id.row21);
        row22 = (SimpleDraweeView) findViewById(R.id.row22);
        row23 = (SimpleDraweeView) findViewById(R.id.row23);
        row24 = (SimpleDraweeView) findViewById(R.id.row24);
        row25 = (SimpleDraweeView) findViewById(R.id.row25);
        row26 = (SimpleDraweeView) findViewById(R.id.row26);
        initListener();
    }

    private void initListener(){
        row11.setOnClickListener(this);
        focusRelativeLayout.setItemViewFocusSearchListener(new FocusRelativeLayout.ItemViewFocusSearchListener() {
            @Override
            public boolean onItemViewFocusSearch(FocusRelativeLayout parent, View itemView, int itemCount, int position, KeyEvent event) {

                int id  = itemView.getId();
                if(event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() != KeyEvent.ACTION_UP){
                    if(R.id.row15 ==  id || id == R.id.row26){
                        focusRelativeLayout.shockAnim(itemView);
                        return true;
                    }
                }

                return false;
            }
        });
//        focusRelativeLayout.setItemViewFocusChangeListener(new FocusRelativeLayout.onItemFocusChangeListener() {
//            @Override
//            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
//                View maskView = itemView.findViewById(R.id.maskView);
//                    if (hasFocus) {
//                        if(maskView != null){
//                            maskView.setVisibility(INVISIBLE);
//
//                        }
//                    } else {
//                        if(maskView != null){
//                            maskView.setVisibility(VISIBLE);
//                        }
//                    }
//                }
//        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.row11:
                AppUtil.playEnter = PageName+"_1_1";
                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "1_1", "", "生活屏直播坑口");
                IntentMap.startIntent(mContext,null,"LiveActivity",liveUrl,null);
                break;
        }
    }

    @Override
    public void getLoopDataSuccess(AssetsDataModel mData) {
        if(mData!=null && !TextUtils.isEmpty(mData.getJsonUrl()))
            liveUrl = mData.getJsonUrl();
        if(mData!=null && !TextUtils.isEmpty(mData.getPicUrl()))
            FrescoImageFetcherModule.getInstance().attachImage(mData.getPicUrl(), row11);
    }

    /**
     * 第一排数据获取成功
     * @param mData
     */
    @Override
    public void getDataSuccess1(final List<AssetsDataModel> mData) {
        if(mData!=null){
            int count = mData.size();
            for(int i=0;i<count;i++){
                if(mData.get(i)!=null){
                    switch (i){
                        case 0:
                            FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row12);
                            final int finalI = i;
                            row12.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    AppUtil.playEnter = PageName+"_1_"+(finalI +2);
                                    WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "1_"+(finalI+2),
                                            mData.get(finalI).getId()+"", mData.get(finalI).getTitle());
                                    WasuStatistics.getInstance().click(mData.get(finalI).getId()+"");

                                    String layoutCode = mData.get(0).getLayout();
                                    String jsonUrl = mData.get(0).getJsonUrl();
                                    IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                                }
                            });
                            break;
                        case 1:
                            FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row13);
                            final int finalI1 = i;
                            row13.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    AppUtil.playEnter = PageName+"_1_"+(finalI1 +2);
                                    WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "1_"+(finalI1 +2),
                                            mData.get(finalI1).getId()+"", mData.get(finalI1).getTitle());
                                    WasuStatistics.getInstance().click(mData.get(finalI1).getId()+"");

                                    String layoutCode = mData.get(1).getLayout();
                                    String jsonUrl = mData.get(1).getJsonUrl();
                                    IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                                }
                            });
                            break;
                        case 2:
                            FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row14);
                            final int finalI2 = i;
                            row14.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    AppUtil.playEnter = PageName+"_1_"+(finalI2 +2);
                                    WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "1_"+(finalI2 +2),
                                            mData.get(finalI2).getId()+"", mData.get(finalI2).getTitle());
                                    WasuStatistics.getInstance().click(mData.get(finalI2).getId()+"");

                                    String layoutCode = mData.get(2).getLayout();
                                    String jsonUrl = mData.get(2).getJsonUrl();
                                    IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                                }
                            });
                            break;
                        case 3:
                            FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row15);
                            final int finalI3 = i;
                            row15.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    AppUtil.playEnter = PageName+"_1_"+(finalI3 +2);
                                    WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "1_"+(finalI3 +2),
                                            mData.get(finalI3).getId()+"", mData.get(finalI3).getTitle());
                                    WasuStatistics.getInstance().click(mData.get(finalI3).getId()+"");


                                    String layoutCode = mData.get(3).getLayout();
                                    String jsonUrl = mData.get(3).getJsonUrl();
                                    IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                                }
                            });
                            break;
                    }
                }
            }
        }
    }

    @Override
    public void getDataSuccess2(final List<AssetsDataModel> mData) {
        if(mData == null)
            return;
        int count = mData.size();
        for(int i=0;i<count;i++){
            if(mData.get(i)!=null){
                switch (i){
                    case 0:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row21);
                        final int finalI = i;
                        row21.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI +1),
                                        mData.get(finalI).getId()+"", mData.get(finalI).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI).getId()+"");

                                String layoutCode = mData.get(0).getLayout();
                                String jsonUrl = mData.get(0).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                    case 1:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row22);
                        final int finalI1 = i;
                        row22.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI1 +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI1 +1),
                                        mData.get(finalI1).getId()+"", mData.get(finalI1).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI1).getId()+"");

                                String layoutCode = mData.get(1).getLayout();
                                String jsonUrl = mData.get(1).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                    case 2:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row23);
                        final int finalI2 = i;
                        row23.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI2 +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI2 +1),
                                        mData.get(finalI2).getId()+"", mData.get(finalI2).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI2).getId()+"");

                                String layoutCode = mData.get(2).getLayout();
                                String jsonUrl = mData.get(2).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                    case 3:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row24);
                        final int finalI3 = i;
                        row24.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI3 +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI3 +1),
                                        mData.get(finalI3).getId()+"", mData.get(finalI3).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI3).getId()+"");

                                String layoutCode = mData.get(3).getLayout();
                                String jsonUrl = mData.get(3).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                    case 4:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row25);
                        final int finalI4 = i;
                        row25.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI4 +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI4 +1),
                                        mData.get(finalI4).getId()+"", mData.get(finalI4).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI4).getId()+"");

                                String layoutCode = mData.get(4).getLayout();
                                String jsonUrl = mData.get(4).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                    case 5:
                        FrescoImageFetcherModule.getInstance().attachImage(mData.get(i).getPicUrl(), row26);
                        final int finalI5 = i;
                        row26.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppUtil.playEnter = PageName+"_2_"+(finalI5 +1);
                                WasuStatistics.getInstance().homeItemClick(viewPager.getCurrentItem(), PageName, "2_"+(finalI5 +1),
                                        mData.get(finalI5).getId()+"", mData.get(finalI5).getTitle());
                                WasuStatistics.getInstance().click(mData.get(finalI5).getId()+"");

                                String layoutCode = mData.get(5).getLayout();
                                String jsonUrl = mData.get(5).getJsonUrl();
                                IntentMap.startIntent(mContext,null,layoutCode,jsonUrl,null);
                            }
                        });
                        break;
                }
            }
        }
    }

    @Override
    public void getDataError(int errorCode, String errorMsg) {

    }

    /**
     * 第一次请求焦点
     * @param direction
     */
    @Override
    public void firstRequestFocus(int direction ){
        onRequestFocusInDescendants(direction ,null);
    }

    @Override
    public void changeViewPager(int viewPagerPosition) {

    }

    @Override
    public void scrollToTop() {

    }

    @Override
    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
        if(previouslyFocusedRect==null && direction == View.FOCUS_DOWN){
            if(row11!=null){
                row11.requestFocus();
                return true;
            }
        }
        return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
    }

    /***********************************************************************************************/
    /**
     * 回收和显示页面上的图片资源，减少内存占用
     */
    final Handler imageViewHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            if(MSG_RecycleImageView == what){
                recycleImageViewTask();
            }else if(MSG_ShowImageView == what){
                showImageViewTask();
            }
            return false;
        }
    });
    public void recycleImageView(){
        imageViewHandler.removeMessages(MSG_ShowImageView);
        imageViewHandler.removeMessages(MSG_RecycleImageView);
        if(isRecycled)
            return;
        imageViewHandler.sendEmptyMessageDelayed(MSG_RecycleImageView, 600);
    }

    public void showImageView(){
        imageViewHandler.removeMessages(MSG_ShowImageView);
        imageViewHandler.removeMessages(MSG_RecycleImageView);
        if(!isRecycled)
            return;
        imageViewHandler.sendEmptyMessageDelayed(MSG_ShowImageView, 600);
    }

    private void recycleImageViewTask(){

        //具体回收

        isRecycled = true;
    }

    private void showImageViewTask(){
        isFirst = false;

        //具体显示

        isRecycled = false;
    }
}
