/**
 * @Title: FavoriteActivity.java
 * @Package com.wasu.tvplayersdk.ui
 * @author duhuanbiao
 * @date 2014年10月20日 下午5:36:40
 * @Description:
 */
package com.wasu.cs.ui;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.cs.adapter.FavRecyclerAdapter;
import com.wasu.cs.adapter.HisRecyclerAdapter;
import com.wasu.cs.adapter.OnItemDeleteListener;
import com.wasu.cs.adapter.OnItemFocusChangeListener;
import com.wasu.cs.module.FavAndHisModule;
import com.wasu.cs.widget.AboutUsLayout;
import com.wasu.cs.widget.DialogHisFav;
import com.wasu.cs.widget.FavHisLinearLayout;
import com.wasu.cs.widget.HisFavListScrollView;
import com.wasu.cs.widget.TimeLineView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.RecyclerPauseOnScrollListener;
import com.wasu.module.db.DBBase;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;
import com.wasu.util.ConfigUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramFavorite;
import basic.db.model.DBProgramHistory;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * 收藏和历史公用页面
 */
public class ActivityFavAndHistory extends ActivityBase implements
        View.OnFocusChangeListener, View.OnClickListener, OnItemFocusChangeListener, OnItemDeleteListener {
    private final String TAG = "ActivityFavAndHistory";
    private final String PAGEVIEWTYPES[] = {"History", "Favorite", "AboutUs"};
    private final String PAGENAMES[] = {"历史", "收藏", "关于我们"};
    private final String CATNAME = "历史收藏页";
    public static final String LIGHT = "#ffffff";
    public static final String DARK = "#7fffffff";
    private final static int HIS_DATA_LOADED = 1;
    private final static int FAV_DATA_LOADED = 2;
    private final static int IS_VIP = 3;
    private final static int NOT_VIP = 4;
    private final static int NO_LOGIN = 5;

    // 数组长度代表点击次数
    long[] mHits = new long[5];

    private List<RowData> mRowDatasHis, mRowDatasFav;
    private List<TextView> titlesHis, titlesFav;
    private List<RecyclerView> recyclerViewsHis, recyclerViewsFav;
    private List<TimeLineView> timeLineViewsHis, timeLineViewsFav;

    private boolean hisWaiting = true, favWating = true;
    //menu
    private FavHisLinearLayout favhisgroupLayout;
    private ImageView userIcon;
    private TextView tips;
    private TextView mHisTextView;
    private TextView mFavTextView;
    private TextView mAboutUs;//关于我们

    private TextView mNoContentTextview;

    private ImageView mDelAllImageView;
    private TextView mDelAllTextView;
    private HisFavListScrollView mHisContentView, mFavContentView;
    private AboutUsLayout mAboutUsLayout;//关于我们的视图

    private Intent intent;
    // 0代表历史，1代表收藏
    private final int TO_HISTORY = 2;
    private final int TO_FAVORITE = 3;
    private final int TO_ABOUTUS = 4;
    private int currentPage = TO_HISTORY;

    private int mItemHeight;
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HIS_DATA_LOADED:
                    mRowDatasHis = (List<RowData>) msg.obj;
                    if (mRowDatasHis != null && mRowDatasHis.size() > 0) {
                        HisAdapter adapter = new HisAdapter();
                        mHisContentView.setAdapter(adapter);
                        if (mRowDatasHis.size() == 1) {
                            TimeLineView line = new TimeLineView(ActivityFavAndHistory.this);
                            line.setRadius(0);
                            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                    mItemHeight);
                            line.setLayoutParams(layoutParams);
                            View view = new View(ActivityFavAndHistory.this);
                            view.setLayoutParams(layoutParams);
                            mHisContentView.addChildView(line, view);
                        }
                    }
                    hisWaiting = false;
                    if (currentPage == TO_HISTORY) {
                        showHistory();
                    }
                    break;
                case FAV_DATA_LOADED:
                    mRowDatasFav = (List<RowData>) msg.obj;
                    if (mRowDatasFav != null && mRowDatasFav.size() > 0) {
                        FavAdapter adapter = new FavAdapter();
                        mFavContentView.setAdapter(adapter);
                        if (mRowDatasFav.size() == 1) {
                            TimeLineView line = new TimeLineView(ActivityFavAndHistory.this);
                            line.setRadius(0);
                            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                    mItemHeight);
                            line.setLayoutParams(layoutParams);
                            View view = new View(ActivityFavAndHistory.this);
                            view.setLayoutParams(layoutParams);
                            mFavContentView.addChildView(line, view);
                        }
                    }
                    favWating = false;
                    if (currentPage == TO_FAVORITE) {
                        showFavorite();
                    }
                    break;
                case IS_VIP:
                    tips.setText("续订有优惠");
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                            (int) getResources().getDimension(R.dimen.d_130dp),
                            (int) getResources().getDimension(R.dimen.d_30dp));
                    layoutParams.setMargins(0, (int) getResources().getDimension(R.dimen.d_13dp), 0, 0);
                    layoutParams.gravity = Gravity.CENTER;
                    tips.setLayoutParams(layoutParams);
                    FrescoImageFetcherModule.setRouteDisplayImager(userIcon, mHeadUrl);
                    break;
                case NOT_VIP:
                    tips.setText("开通VIP");
                    FrescoImageFetcherModule.setRouteDisplayImager(userIcon, mHeadUrl);
                    break;
                case NO_LOGIN:
                    tips.setText("开通VIP");
                    userIcon.setImageResource(R.drawable.not_login);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WLog.i(TAG,"onCreate()");
        setContentView(R.layout.activity_favorite_history);
        initView();
        hideLoading();
    }

    @Override
    protected void doCreate(Bundle savedInstanceState) {
    }

    private void initData() {
        initHistoryData();
        initFavoriteData();
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (mHisContentView == null && mFavContentView == null) {//无网络时防crash
            return;
        }

        bindUserData();
        initData();

        if (currentPage == TO_HISTORY) {
            mHisTextView.requestFocus();
        } else if (currentPage == TO_FAVORITE) {
            mFavTextView.requestFocus();
        }
        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPES[currentPage - 2]);

    }

    @Override
    protected void onPause() {
        super.onPause();
        WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPES[currentPage - 2], CATNAME, PAGENAMES[currentPage - 2]);
    }

    String mHeadUrl = null;

    //绑定用户信息
    public void bindUserData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHeadUrl = ConfigUtils.getString(ActivityFavAndHistory.this, "usercenter", "headUrl");
                // 判断用户是否登录
                if (!TextUtils.isEmpty(mHeadUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_ENCRYPTV) != null && AuthSDK.getInstance().getValue(IAuthInterface.KEY_PUBLICKEY) != null) {
                    if (checkIsVip()) {
                        handler.sendEmptyMessage(IS_VIP);

                    } else {
                        handler.sendEmptyMessage(NOT_VIP);
                    }
                } else {
                    handler.sendEmptyMessage(NO_LOGIN);


                }
            }
        }).start();


    }

    /**
     * 检查是否为VIP用户
     */
    private boolean checkIsVip() {
        String isvip = AuthSDK.getInstance().getValue("vipState");
        if (!TextUtils.isEmpty(isvip)) {
            if ("0".equalsIgnoreCase(isvip)) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public void refresh() {
        if (currentPage == TO_HISTORY) {
            initHistoryData();
            mHisTextView.requestFocus();
        } else if (currentPage == TO_FAVORITE) {
            initFavoriteData();
            mFavTextView.requestFocus();
        }
    }


    private void addtestData() {
        // add history
        for (int i = 0; i < 20; i++) {
            DBProgramHistory history = new DBProgramHistory();
            history.domain = BuildType.HTTP_DOMAIN;
            history.programId = 625280 + i;
            history.programPic = "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2013-04/01/1364791016281_681107.jpg";
            history.programName = "一代宗师";
            history.showType = 1;
            history.savehistorytime = System.currentTimeMillis() - 8 * 24 * 60 * 60 * 1000;
            FavAndHisModule.getInstance().saveHistory(history);
        }
        for (int i = 0; i < 10; i++) {
            DBProgramHistory history = new DBProgramHistory();
            history.domain = BuildType.HTTP_DOMAIN;
            history.programId = 625250 + i;
            history.programPic = "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2013-04/01/1364791016281_681107.jpg";
            history.programName = "一代宗师";
            history.showType = 1;
            history.savehistorytime = System.currentTimeMillis();
            FavAndHisModule.getInstance().saveHistory(history);
        }
        for (int i = 0; i < 5; i++) {
            DBProgramHistory history = new DBProgramHistory();
            history.domain = BuildType.HTTP_DOMAIN;
            history.programId = 625260 + i;
            history.programPic = "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2013-04/01/1364791016281_681107.jpg";
            history.programName = "一代宗师";
            history.showType = 1;
            history.savehistorytime = System.currentTimeMillis() - 24 * 60 * 60 * 1000;
            FavAndHisModule.getInstance().saveHistory(history);
        }
       /* // add favorite
        addOneFavorite(
                1241396,
                "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/30/1419931961331_913496.jpg",
                "一路响叮当2");
        addOneFavorite(
                1241148,
                "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/30/1419924840465_237520.jpg",
                "法官老爸");
        addOneFavorite(
                1214171,
                "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/201412/05/cms_28694886078242895146607.jpg",
                "复仇者联盟(杜比)");
        addOneFavorite(
                1072257,
                "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/201408/27/cms_71296546504936701404569.jpg",
                "上海正午2(杜比)");
        addOneFavorite(
                1202415,
                "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/201411/27/cms_31468647674902880634486.jpg",
                "银河护卫队(国语)");*/

    }

    public void addOneFavorite(int programId, String programPic, String name) {
        DBProgramFavorite favorite = new DBProgramFavorite();
        favorite.domain = BuildType.HTTP_DOMAIN;
        favorite.programId = programId;// 1234291;
        favorite.programPic = programPic;// "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/23/1419319884357_911586.jpg";
        favorite.programName = name;// "猩球崛起2";
        favorite.showType = 1;
        FavAndHisModule.getInstance().saveFavorite(favorite);
    }


    /**
     * 初始化控件，设置监听
     */
    private void initView() {

        mItemHeight = (int) getResources().getDimension(R.dimen.d_303dp);
        favhisgroupLayout = (FavHisLinearLayout) findViewById(R.id.favhisgroup);
        userIcon = (ImageView) findViewById(R.id.userIcon);
        tips = (TextView) findViewById(R.id.tvTips);
        tips.setOnClickListener(this);
        mHisTextView = (TextView) findViewById(R.id.tvHistory);
        mFavTextView = (TextView) findViewById(R.id.tvFavorite);
        mAboutUs = (TextView) findViewById(R.id.tvAboutUs);
        // 设置光标获得光标的监听
        mHisTextView.setOnFocusChangeListener(this);
        mFavTextView.setOnFocusChangeListener(this);
        mAboutUs.setOnFocusChangeListener(this);

        //针对求索的盒子进行的定制化处理
        if (BuildConfig.FLAVOR.equalsIgnoreCase("QiuSuo")) {
            mAboutUs.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 数组依次先前移动一位
                    System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                    mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后运行时间
                    if (mHits[0] >= (mHits[mHits.length - 1] - 1500)) {
                        Toast.makeText(ActivityFavAndHistory.this, "进入系统设置", Toast.LENGTH_LONG).show();
                        //进入自定义的系统设置
                        Intent mIntent = new Intent("android.settings.SETTINGS");
                        startActivity(mIntent);
                    }
                }
            });
        }

        mNoContentTextview = (TextView) findViewById(R.id.tx_no_content);

        mDelAllImageView = (ImageView) findViewById(R.id.del_all_iv);
        mDelAllTextView = (TextView) findViewById(R.id.del_all_tv);

        mAboutUsLayout = (AboutUsLayout) findViewById(R.id.aboutuscontainer);
        mDelAllTextView.setOnFocusChangeListener(this);
        mDelAllTextView.setOnClickListener(this);

        mHisContentView = (HisFavListScrollView) findViewById(R.id.his_content_view);
        mFavContentView = (HisFavListScrollView) findViewById(R.id.fav_content_view);
        // 判断是从历史进来or收藏进来,默认是历史进来
        intent = getIntent();
        String layoutcode = intent.getStringExtra(IntentConstant.LAYOUT_CODE.value());
        int direct = TO_HISTORY;
        if (layoutcode.equals("Wasu_Favorite")) {
            direct = TO_FAVORITE;
        }
        if (direct == TO_HISTORY) {
            currentPage = TO_HISTORY;
            favhisgroupLayout.setIndex(TO_HISTORY);
            mHisTextView.requestFocus();
        } else if (direct == TO_FAVORITE) {
            currentPage = TO_FAVORITE;
            favhisgroupLayout.setIndex(TO_FAVORITE);
            mFavTextView.requestFocus();
        } else if (direct == TO_ABOUTUS) {
            currentPage = TO_ABOUTUS;
            favhisgroupLayout.setIndex(TO_ABOUTUS);
            mAboutUs.requestFocus();
        } else {
            // 逻辑上的死代码
        }
    }

    private void alertDialog() {
        DialogHisFav.Builder builder = new DialogHisFav.Builder(this);
        if (currentPage == TO_FAVORITE) {
            builder.setMessage("确定删除所有收藏记录？");
        } else {
            builder.setMessage("确定删除所有历史记录？");
        }
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                //设置你的操作事项
                if (currentPage == TO_HISTORY) {
                    mRowDatasHis.clear();
                    mHisContentView.removeAllViews();
                    FavAndHisModule.getInstance().deleteAllHistory();
                    showNoContent();
                } else if (currentPage == TO_FAVORITE) {
                    mRowDatasFav.clear();
                    mFavContentView.removeAllViews();
                    FavAndHisModule.getInstance().deleteAllFavorite();
                    showNoContent();
                }
            }
        });

        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mDelAllTextView.requestFocus();
                    }
                });

        builder.create().show();
    }

    private void showNoContent() {
        if (currentPage == TO_HISTORY) {
            mNoContentTextview.setText("您还没有历史记录，快去观看吧！");
            mHisTextView.requestFocus();
        } else {
            mNoContentTextview.setText("您还没有收藏记录，快去添加吧！");
            mFavTextView.requestFocus();
        }
        mNoContentTextview.setVisibility(View.VISIBLE);
        mDelAllImageView.setVisibility(View.GONE);
        mDelAllTextView.setVisibility(View.GONE);
        mHisContentView.setVisibility(View.GONE);
        mFavContentView.setVisibility(View.GONE);
        mAboutUsLayout.setVisibility(View.GONE);
    }

    private void showHistory() {
        if (mRowDatasHis == null || mRowDatasHis.size() <= 0) {
            mNoContentTextview.setText("您还没有历史记录，快去观看吧！");
            if (!hisWaiting) {
                mNoContentTextview.setVisibility(View.VISIBLE);
            }
            mDelAllImageView.setVisibility(View.GONE);
            mDelAllTextView.setVisibility(View.GONE);
            mHisContentView.setVisibility(View.GONE);
            mFavContentView.setVisibility(View.GONE);
        } else {
            if (!hisWaiting) {
                mHisContentView.setVisibility(View.VISIBLE);
                mDelAllImageView.setVisibility(View.VISIBLE);
                mDelAllTextView.setVisibility(View.VISIBLE);
            }
            mFavContentView.setVisibility(View.GONE);
            mNoContentTextview.setVisibility(View.GONE);
            mAboutUsLayout.setVisibility(View.GONE);

        }
    }

    private void showFavorite() {
        if (mRowDatasFav == null || mRowDatasFav.size() <= 0) {
            mNoContentTextview.setText("您还没有收藏记录，快去添加吧！");
            if (!favWating) {
                mNoContentTextview.setVisibility(View.VISIBLE);
            }
            mDelAllImageView.setVisibility(View.GONE);
            mDelAllTextView.setVisibility(View.GONE);
            mHisContentView.setVisibility(View.GONE);
            mFavContentView.setVisibility(View.GONE);
        } else {
            if (!favWating) {
                mFavContentView.setVisibility(View.VISIBLE);
                mDelAllImageView.setVisibility(View.VISIBLE);
                mDelAllTextView.setVisibility(View.VISIBLE);
            }
            mHisContentView.setVisibility(View.GONE);
            mNoContentTextview.setVisibility(View.GONE);
            mAboutUsLayout.setVisibility(View.GONE);
        }
    }

    /**
     * author chenming
     */
    private void showAboutUs() {
        mHisContentView.setVisibility(View.GONE);
        mFavContentView.setVisibility(View.GONE);
        mNoContentTextview.setVisibility(View.GONE);
        mDelAllImageView.setVisibility(View.GONE);
        mDelAllTextView.setVisibility(View.GONE);
        mAboutUsLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.tvHistory:
                if (hasFocus) {// 历史获得焦点
                    AppUtil.playEnter = "看过";
                    viewGroupReset(viewGroup);
                    viewGroup = null;
                    showHistory();
                    // 设置下次layout获得光标后定位的位置
                    favhisgroupLayout.setIndex(TO_HISTORY);
                    // 历史不允许编辑，隐藏编辑button
                    currentPage = TO_HISTORY;
                    if (favhisgroupLayout.getDirection() == View.FOCUS_UP||favhisgroupLayout.getDirection()==View.FOCUS_DOWN) {
                        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPES[currentPage - 2]);
                    }
                    setLineByIndex(-1);
                    setTitleByIndex(-1, -1);
                    mFavTextView.setSelected(false);
                } else {// 历史按钮失去焦点
                    // 光标移动到下面后，设置字体颜色
                    if (favhisgroupLayout.getDirection() == View.FOCUS_RIGHT) {
                        v.setSelected(true);
                    } else {
                        v.setSelected(false);
                        WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPES[currentPage - 2], CATNAME, PAGENAMES[currentPage - 2]);
                    }
                }
                break;
            case R.id.tvFavorite:
                if (hasFocus) {// 收藏获得焦点
                    AppUtil.playEnter = "收藏";
                    viewGroupReset(viewGroup);
                    viewGroup = null;
                    showFavorite();
                    favhisgroupLayout.setIndex(TO_FAVORITE);
                    // initFavoriteData(false);
                    currentPage = TO_FAVORITE;
                    if (favhisgroupLayout.getDirection() == View.FOCUS_UP||favhisgroupLayout.getDirection()==View.FOCUS_DOWN) {
                        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPES[currentPage - 2]);
                    }
                    setLineByIndex(-1);
                    setTitleByIndex(-1, -1);
                    mHisTextView.setSelected(false);
                    mAboutUs.setSelected(false);
                } else {// 收藏按钮失去焦点
                    // 光标移动到下面后，设置字体颜色
                    if (favhisgroupLayout.getDirection() == View.FOCUS_RIGHT) {
                        v.setSelected(true);
                    } else {
                        WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPES[currentPage - 2], CATNAME, PAGENAMES[currentPage - 2]);
                        v.setSelected(false);
                    }
                }
                break;
            case R.id.tvAboutUs:
                if (hasFocus) {//关于我们获得焦点
                    showAboutUs();
                    favhisgroupLayout.setIndex(TO_ABOUTUS);
                    currentPage = TO_ABOUTUS;
                    if (favhisgroupLayout.getDirection() == View.FOCUS_UP||favhisgroupLayout.getDirection()==View.FOCUS_DOWN) {
                        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPES[currentPage - 2]);
                    }
                    mFavTextView.setSelected(false);
                } else {//关于我们失去焦点
                    // 光标移动到下面后，设置字体颜色
                    if (favhisgroupLayout.getDirection() == View.FOCUS_RIGHT) {
                        v.setSelected(true);
                    } else {
                        WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPES[currentPage - 2], CATNAME, PAGENAMES[currentPage - 2]);
                        v.setSelected(false);
                    }
                }
                break;
            case R.id.tvTips:
                if (hasFocus) {
                    tips.setBackgroundResource(R.drawable.vip_yellow);
                } else {
                    tips.setBackgroundResource(R.drawable.vip_white);
                }
                break;
            case R.id.del_all_tv:
                if (hasFocus) {
                    viewGroupReset(viewGroup);
                    setLineByIndex(-1);
                    setTitleByIndex(-1, -1);
                    mDelAllTextView.setText("按OK键清空");
                    mDelAllImageView.setSelected(true);
                } else {
                    mDelAllTextView.setText("全部删除");
                    mDelAllImageView.setSelected(false);
                }
            default:
                break;
        }
    }

    /**
     * 初始化历史数据，并设置Adapter
     **/
    private void initHistoryData() {
        mRowDatasHis = new ArrayList<>();
        titlesHis = new ArrayList<>();
        timeLineViewsHis = new ArrayList<>();
        recyclerViewsHis = new ArrayList<>();
        mCurIndexHis = -1;
        new Thread(new FetchDataTask<DBProgramHistory>() {
            @Override
            List<DBProgramHistory> readData() {
                return FavAndHisModule.getInstance().readHistory();
            }

            @Override
            void splitToThreeList(List<DBProgramHistory> list, List<DBProgramHistory> listDay, List<DBProgramHistory> listWeek, List<DBProgramHistory> listMore) {
                for (DBProgramHistory dbProgramHistory : list) {
                    long hisTime = dbProgramHistory.savehistorytime;
                    if (isToday(hisTime)) {
                        listDay.add(dbProgramHistory);
                    } else if (isThisWeek(hisTime)) {
                        listWeek.add(dbProgramHistory);
                    } else {
                        listMore.add(dbProgramHistory);
                    }
                }
            }

            @Override
            void sendDataLoadedMsg(List<RowData> rowDatas) {
                Message msg = Message.obtain(handler);
                msg.what = HIS_DATA_LOADED;
                msg.obj = rowDatas;
                msg.sendToTarget();
            }
        }).start();
    }


    /**
     * 初始化收藏数据，并设置Adapter
     **/
    private void initFavoriteData() {
        mRowDatasFav = new ArrayList<>();
        titlesFav = new ArrayList<>();
        timeLineViewsFav = new ArrayList<>();
        recyclerViewsFav = new ArrayList<>();
        mCurIndexHis = -1;
        new Thread(new FetchDataTask<DBProgramFavorite>() {
            @Override
            List<DBProgramFavorite> readData() {
                return FavAndHisModule.getInstance().readFavorite();
            }

            @Override
            void splitToThreeList(List<DBProgramFavorite> list, List<DBProgramFavorite> listDay, List<DBProgramFavorite> listWeek, List<DBProgramFavorite> listMore) {
                for (DBProgramFavorite dbProgramFavorite : list) {
                    long hisTime = dbProgramFavorite.savefavoritetime;
                    if (isToday(hisTime)) {
                        listDay.add(dbProgramFavorite);
                    } else if (isThisWeek(hisTime)) {
                        listWeek.add(dbProgramFavorite);
                    } else {
                        listMore.add(dbProgramFavorite);
                    }
                }
            }

            @Override
            void sendDataLoadedMsg(List<RowData> rowDatas) {
                Message msg = Message.obtain(handler);
                msg.what = FAV_DATA_LOADED;
                msg.obj = rowDatas;
                msg.sendToTarget();
            }
        }).start();
    }

    ViewGroup viewGroup = null;

    void viewGroupReset(ViewGroup viewGroup) {
        if (viewGroup != null) {
            if (viewGroup.getChildAt(1) != null)
                viewGroup.getChildAt(1).setVisibility(View.GONE);
            viewGroup.setScaleX(1F);
            viewGroup.setScaleY(1F);
        }
    }

    private int mCurPos = -1;

    @Override
    public void onItemFocusChange(ViewGroup vG, int pos, boolean hasfocus, int index) {
        if (hasfocus) {
            if (vG != viewGroup) {
                viewGroupReset(viewGroup);
            }
            mCurPos = pos;
            viewGroup = vG;
            setLineByIndex(index);
            setTitleByIndex(index, pos);
        }
    }

    @Override
    public void onFirstItemFocusLeft() {
        if (currentPage == TO_HISTORY) {
            mHisTextView.requestFocus();
        } else if (currentPage == TO_FAVORITE) {
            mFavTextView.requestFocus();
        }
    }

    /**
     * @param index 第几个recyclerview
     * @param pos   recyclerview中的位置
     */
    public void setRecyclerViewItemFocus(int index, final int pos) {
        if (currentPage == TO_HISTORY) {
            if (index < recyclerViewsHis.size()) {
                final RecyclerView recyclerView = recyclerViewsHis.get(index);
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        View view = recyclerView.getLayoutManager().findViewByPosition(pos);
                        if (view != null) {
                            view.requestFocus();
                        }
                    }
                }, 200);
            }
        } else if (currentPage == TO_FAVORITE) {
            if (index < recyclerViewsFav.size()) {
                final RecyclerView recyclerView = recyclerViewsFav.get(index);
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        View view = recyclerView.getLayoutManager().findViewByPosition(pos);
                        if (view != null) {
                            view.requestFocus();
                        }
                    }
                }, 200);
            }
        }
    }

    @Override
    public void onItemDelete(int pos, int index) {
        setRecyclerViewItemFocus(index, pos);
    }

    @Override
    public void onAllItemDelete() {
        refresh();
    }


    abstract class FetchDataTask<T extends DBBase> implements Runnable {

        @Override
        public void run() {
            List<T> list = readData();
            List<RowData> rowDatas = new ArrayList<>();
            if (list != null && list.size() > 0) {
                List<T> listDay = new ArrayList<>();
                List<T> listWeek = new ArrayList<>();
                List<T> listMore = new ArrayList<>();

                splitToThreeList(list, listDay, listWeek, listMore);

                if (listDay != null && listDay.size() > 0) {
                    rowDatas.add(new RowData(listDay, "今天"));
                }
                if (listWeek != null && listWeek.size() > 0) {
                    rowDatas.add(new RowData(listWeek, "7天内"));
                }
                if (listMore != null && listMore.size() > 0) {
                    rowDatas.add(new RowData(listMore, "更早"));
                }
            }
            sendDataLoadedMsg(rowDatas);

        }

        abstract List<T> readData();

        abstract void splitToThreeList(List<T> list, List<T> listDay, List<T> listWeek, List<T> listMore);

        abstract void sendDataLoadedMsg(List<RowData> rowDatas);
    }

    //获得0点时间戳
    public long getZeroTime(){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }

    private boolean isToday(long hisTime) {
        long zero = getZeroTime();
        return (hisTime >= zero && hisTime < zero + 1000 * 60 * 60 * 24);
    }

    private boolean isThisWeek(long hisTime) {
        long zero = getZeroTime();
        return (hisTime < zero && hisTime > zero - 7 * 1000 * 3600 * 24);
    }


    @Override
    public void onBackPressed() {
        if (mHisTextView != null && !mHisTextView.hasFocus()
                && mFavTextView != null && !mFavTextView.hasFocus()
                && mAboutUs != null && !mAboutUs.hasFocus()
                && tips != null && !tips.hasFocus()) {
            if (currentPage == TO_HISTORY) {
                mHisTextView.requestFocus();
            } else if (currentPage == TO_FAVORITE) {
                mFavTextView.requestFocus();
            } else if (currentPage == TO_ABOUTUS) {
                mAboutUs.requestFocus();
            }
        } else {
            super.onBackPressed();
        }
    }

    private int mCurIndexHis = -1;
    private int mCurIndexFav = -1;

    public void setLineByIndex(int index) {
        if (currentPage == TO_HISTORY) {
            if (index != mCurIndexHis) {
                if (index >= 0 && index < timeLineViewsHis.size()) {
                    TimeLineView view = timeLineViewsHis.get(index);
                    view.setPaintCircleColor(LIGHT);
                }

                if (mCurIndexHis >= 0 && mCurIndexHis < timeLineViewsHis.size()) {
                    TimeLineView curView = timeLineViewsHis.get(mCurIndexHis);
                    curView.setPaintCircleColor(DARK);
                }
            }
        } else if (currentPage == TO_FAVORITE) {
            if (index != mCurIndexFav) {
                if (index >= 0 && index < timeLineViewsFav.size()) {
                    TimeLineView view = timeLineViewsFav.get(index);
                    view.setPaintCircleColor(LIGHT);
                }

                if (mCurIndexFav >= 0 && mCurIndexFav < timeLineViewsFav.size()) {
                    TimeLineView curView = timeLineViewsFav.get(mCurIndexFav);
                    curView.setPaintCircleColor(DARK);
                }
            }
        }
    }


    public void setTitleByIndex(int index, int pos) {
        if (currentPage == TO_HISTORY) {
            if (index >= 0 && index < titlesHis.size()) {
                TextView view = titlesHis.get(index);
                view.setTextColor(Color.parseColor(LIGHT));
                view.setText(mRowDatasHis.get(index).getTitle() + " " + (pos + 1) + "|" + mRowDatasHis.get(index).getList().size());
            }
            if (index != mCurIndexHis) {
                if (mCurIndexHis >= 0 && mCurIndexHis < titlesHis.size()) {
                    TextView view = titlesHis.get(mCurIndexHis);
                    view.setTextColor(Color.parseColor(DARK));
                    view.setText(mRowDatasHis.get(mCurIndexHis).getTitle());
                }
                mCurIndexHis = index;
            }
        } else if (currentPage == TO_FAVORITE) {
            if (index >= 0 && index < titlesFav.size()) {
                TextView view = titlesFav.get(index);
                view.setTextColor(Color.parseColor(LIGHT));
                view.setText(mRowDatasFav.get(index).getTitle() + " " + (pos + 1) + "|" + mRowDatasFav.get(index).getList().size());
            }
            if (index != mCurIndexFav) {
                if (mCurIndexFav >= 0 && mCurIndexFav < titlesFav.size()) {
                    TextView view = titlesFav.get(mCurIndexFav);
                    view.setTextColor(Color.parseColor(DARK));
                    view.setText(mRowDatasFav.get(mCurIndexFav).getTitle());
                }
                mCurIndexFav = index;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvTips:
                IntentMap.startIntent(ActivityFavAndHistory.this, null, "Wasu_UserCenter", Common.UserCenterUrl, null);
                break;
            case R.id.del_all_tv:
                alertDialog();
                break;
            default:
                break;
        }
    }


    class RowData<T extends DBBase> {
        List<T> mList;
        String mTitle;

        public RowData(List<T> list, String title) {
            mList = list;
            mTitle = title;
        }

        public String getTitle() {
            return mTitle;
        }

        public List<T> getList() {
            return mList;
        }
    }


    class HisAdapter extends HisFavListScrollView.Adapter {


        @Override
        public View getContainerView(int pos) {
            View view = LayoutInflater.from(ActivityFavAndHistory.this).inflate(R.layout.item_his_fav_row_layout, null);
            HisRecyclerAdapter adapter = new HisRecyclerAdapter(mRowDatasHis.get(pos).getList(), ActivityFavAndHistory.this, pos);
            adapter.setOnItemFocusChangeListener(ActivityFavAndHistory.this);
            adapter.setOnItemClickListener(ActivityFavAndHistory.this);
            RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
            LinearLayoutManager layoutManager = new LinearLayoutManager(ActivityFavAndHistory.this, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
            recyclerView.addOnScrollListener(new RecyclerPauseOnScrollListener(true,true));
            TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
            tv_title.setText(mRowDatasHis.get(pos).getTitle());
            recyclerViewsHis.add(recyclerView);
            titlesHis.add(tv_title);
            return view;
        }

        @Override
        public View getTimelineView(int pos) {
            TimeLineView timeLineView = new TimeLineView(ActivityFavAndHistory.this);
            if (pos == 0) {
                timeLineView.setIsFirst(true);
            }
            timeLineViewsHis.add(timeLineView);
            return timeLineView;
        }

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

    class FavAdapter extends HisFavListScrollView.Adapter {

        @Override
        public View getContainerView(int pos) {
            View view = LayoutInflater.from(ActivityFavAndHistory.this).inflate(R.layout.item_his_fav_row_layout, null);
            FavRecyclerAdapter adapter = new FavRecyclerAdapter(ActivityFavAndHistory.this, mRowDatasFav.get(pos).getList(), pos);
            adapter.setOnItemFocusChangeListener(ActivityFavAndHistory.this);
            adapter.setOnItemClickListener(ActivityFavAndHistory.this);
            RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
            LinearLayoutManager layoutManager = new LinearLayoutManager(ActivityFavAndHistory.this, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
            TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
            tv_title.setText(mRowDatasFav.get(pos).getTitle());
            recyclerViewsFav.add(recyclerView);
            titlesFav.add(tv_title);
            return view;
        }

        @Override
        public View getTimelineView(int pos) {
            TimeLineView timeLineView = new TimeLineView(ActivityFavAndHistory.this);
            if (pos == 0) {
                timeLineView.setIsFirst(true);
            }
            timeLineViewsFav.add(timeLineView);
            return timeLineView;
        }

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


}
