package com.sheep.gamegroup.view.fragment;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.transition.ChangeBounds;
import android.transition.TransitionManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.di.components.DaggerSmallSheepComponent;
import com.sheep.gamegroup.di.modules.SmallSheepModule;
import com.sheep.gamegroup.di.modules.TryMakeMoneyModule;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.BulletinEnty;
import com.sheep.gamegroup.model.entity.CashAwarsEntity;
import com.sheep.gamegroup.model.entity.HomeListEntity;
import com.sheep.gamegroup.model.entity.MessageUnReadEntity;
import com.sheep.gamegroup.model.entity.MoreDataEntity;
import com.sheep.gamegroup.model.entity.RecyleObj;
import com.sheep.gamegroup.model.entity.RecyleType;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.entity.RequestParamEty;
import com.sheep.gamegroup.model.entity.RobTask;
import com.sheep.gamegroup.model.entity.SlideshowEty;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.presenter.SmallSheepContract;
import com.sheep.gamegroup.presenter.SmallSheepPresenter;
import com.sheep.gamegroup.presenter.TryMakeMoneyContract;
import com.sheep.gamegroup.presenter.TryMakeMoneyPresenter;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ConfigUtil;
import com.sheep.gamegroup.util.DataKey;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.ActMsg;
import com.sheep.gamegroup.view.activity.NotificationsUtils;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.AdpHomeListGrideview;
import com.sheep.gamegroup.view.adapter.AdpHomeListListview;
import com.sheep.gamegroup.view.adapter.AdpTryMakemoney;
import com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp;
import com.sheep.gamegroup.view.dialog.DialogNewbieTaskList;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.NEWBIE_TASK;

public class FgtSmallSheep extends BaseFragment implements SmallSheepContract.View, TryMakeMoneyContract.View {

    @BindView(R.id.upview1)
    MarqueeView upview1;
    Unbinder unbinder;
    @BindView(R.id.homepage_item_notice_mv)
    MarqueeView homepageItemNoticeMv;
    @BindView(R.id.homepage_item_notice_layout)
    LinearLayout homepageItemNoticeLayout;
    @BindView(R.id.banner)
    Banner banner;

    @BindView(R.id.icon_img_iv)
    ImageView iconImgIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.sheep_num_tv)
    TextView sheepNumTv;
    @BindView(R.id.withdrawal)
    TextView withdrawal;
    @BindView(R.id.my_price)
    TextView myPrice;
    @BindView(R.id.try_play_layout)
    LinearLayout tryPlayLayout;
    @BindView(R.id.invitation_layout)
    LinearLayout invitationLayout;
    @BindView(R.id.lying_layout)
    LinearLayout lyingLayout;
    @BindView(R.id.card_layout)
    LinearLayout card_layout;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.newbie_task)
    View newbie_task;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.recharge)
    TextView recharge;
    @BindView(R.id.home_list_gridview_gv)
    MyGridview home_list_gridview_gv;
    @BindView(R.id.home_list_gridview_listview)
    MyListview home_list_gridview_listview;
    @BindView(R.id.home_list_gridview_layout)
    LinearLayout home_list_gridview_layout;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.bg_newbie_task)
    ImageView bg_newbie_task;
    @BindView(R.id.view_rob_duty)
    View viewRobDuty;
    @BindView(R.id.iv_rob_duty)
    ImageView ivDuty;
    @BindView(R.id.viewpager_act_game_details)
    ViewPager mViewPager;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.homepage_item_get_award_name_tv)
    TextView homepage_item_get_award_name_tv;
    @BindView(R.id.homepage_item_money_tv)
    TextView homepage_item_money_tv;
    @BindView(R.id.homepage_item_juan_tv)
    TextView homepage_item_juan_tv;
    @BindView(R.id.recyclerview_line)
    View recyclerview_line;
    @BindView(R.id.full_home_list_rv)
    RecyclerView full_home_list_rv;
    @BindView(R.id.test_change)
    TextView test_change;
    @BindView(R.id.test_change_user)
    TextView test_change_user;
    @BindView(R.id.list_title)
    LinearLayout listTitle;
    @BindView(R.id.to_search_but_rl)
    View to_search_but_rl;
    @BindView(R.id.to_search_but)
    LinearLayout to_search_but;
    @BindView(R.id.title_car)
    LinearLayout titleCardLayout;
    /* 记录滑动坐标的数组 */
    int[] locate = new int[2];

    @Inject
    SmallSheepPresenter pagePresenter;
    @Inject
    TryMakeMoneyPresenter tryMakeMoneyPresenter;
    private Activity activity;
    private UserEntity userEntity;
    List<View> views = new ArrayList<>();

    //recyclerview
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private List<TaskAcceptedEty> allTaskAcceptedTaskList = ListUtil.emptyList();
    private List<Release_task> releaseEtyLists = new ArrayList<>();
    private List<SlideshowEty> slideshowEtyLists = new ArrayList<>();
    private List<String> slideshowTitleList = new ArrayList<>();
    private List<BulletinEnty> bulletinEntyLists = new ArrayList<>();

    private List<HomeListEntity> homeListEntitys = new ArrayList<>();
    private List<HomeListEntity> fullHomeList = new ArrayList<>();
    private List<HomeListEntity> homeListEntitysGridview = new ArrayList<>();
    private List<HomeListEntity> homeListEntitysListview = new ArrayList<>();
    private AdpHomeListGrideview adpHomeListGrideview;
    private AdpHomeListListview adpHomeListListview;
    private Release_task taskEty;
    private AdpTryMakemoney mAdapter;

    private static final int LIST_COUNT = 2;//tryMakeMoneyAdp 总共有2条数据
    private static final RecyleObj NULL = RecyleObj.make(RecyleType.NONE, null);//空数据
    public static final int WHAT_LOAD_USER_INFO = 0;//加载用户信息
    public static final int WHAT_LOAD_RUN_TASK = 1;//加载正在进行的任务列表
    public static final int WHAT_TRY_SHOW_HB = 7;//尝试显示红包

    private int clickCount = 0;
    public Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            checkAndInitView();
            switch (msg.what) {
                case WHAT_LOAD_USER_INFO:
                    loadUserInfo();
                    break;
                case WHAT_LOAD_RUN_TASK:
                    tryMakeMoneyAdp.clear();
                    //正在进行中的任务列表
                    boolean isAcceptedTaskListEmpty = ListUtil.isEmpty(allTaskAcceptedTaskList);
                    if (!isAcceptedTaskListEmpty) {
                        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, allTaskAcceptedTaskList));
                    }
                    //正在进行中的任务下面的线是否显示
                    if (recyclerview_line != null)
                        recyclerview_line.setVisibility(isAcceptedTaskListEmpty ? View.GONE : View.VISIBLE);

                    //发布的任务列表----注：3.0开始已经没有展示，使用viewpager展示
                    if (!ListUtil.isEmpty(releaseEtyLists)) {
                        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RELEASE_TASK, releaseEtyLists));
                    }
                    tryMakeMoneyAdp.notifyDataSetChanged();
                    break;
                case WHAT_TRY_SHOW_HB:
                    isShowRedPackages(activity);
                    break;
            }

        }
    };
    private TextView doIt;
    private TextView willStart;
    private View doItLine;
    private LinearLayout lines;

    /**
     * @return 是否显示兑换邀请码红包
     */
    private void isShowRedPackageWithCode() {
        //  DataUtil.getInstance().是官方包吗();
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
//userEntity.getParent_code()获取到的不会存在null，没有时，时"",所以不用判断为null的情况
        if (!userEntity.getParent_code().equals("") || (userEntity.getCreate_time_line() < 2) || (userEntity.getPackage_cate() == 1)) {

        } else {
            changeRedPackage(activity, LayoutInflater.from(activity.getApplicationContext()).inflate(R.layout.find_item_bottom, null), this);
        }

    }

     /**
     * 兑换红包弹窗
     *
     * @param mActivity 当前Activity的，
     */
    public static void changeRedPackage(final Activity mActivity, View viewAnchor, final FgtSmallSheep fgtSmallSheep) {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_get_redpackage, null);
        final EditText edInvitationCode = view.findViewById(R.id.ed_invitation_code);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        final TextView tvGetRedPackage = view.findViewById(R.id.tv_get_redpackage);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.7f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new ViewUtil.PopDismissListener(mActivity));
        tvTitle.setText("邀请码领取，金额更大");
        tvGetRedPackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edInvitationCode.getText())) {
                    G.showToast("邀请码不能为空！");
                } else {
                    fgtSmallSheep.getRedPackage(edInvitationCode.getText().toString(), popupWindow);
                    popupWindow.dismiss();
                }
            }
        });
        edInvitationCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                // 获取系统剪贴板
                ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 获取剪贴板的剪贴数据集
                ClipData clipData = clipboard.getPrimaryClip();

                if (clipData != null && clipData.getItemCount() > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    CharSequence codetext = clipData.getItemAt(0).getText();
                    if (!TextUtils.isEmpty(codetext)) {
                        edInvitationCode.setText(codetext);
                    }
                }
                return false;
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
    }

    @OnClick(R.id.to_search_but)
    public void toSearchActivity() {
        Jump2View.getInstance().goAppTaskSearch(activity, null);
    }
    @OnClick(R.id.home_search_msg_iv)
    public void toActMsg() {
        startActivity(new Intent(activity, ActMsg.class));
    }

    /**
     * 兑换红包
     *
     * @param code ,邀请码
     */
    public void getRedPackage(String code, final PopupWindow popupWindow) {
        SheepApp.getInstance().getNetComponent().getApiService().exchangeRedPackage(code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
//                        LogUtil.logI("0------" + new Gson().toJson(baseMessage));
                        G.showToast(baseMessage.getMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        showRedPackageAfterInvitation(activity, LayoutInflater.from(getContext()).inflate(R.layout.find_item_bottom, null), baseMessage);
                        if (popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                    }
                });
    }

    /**
     * 邀请成功后在个人资料显示领红包弹窗
     *
     * @param mActivity 当前Activity
     */
    public void showRedPackageAfterInvitation(final Activity mActivity, View viewAnchor, BaseMessage baseMessage) {
        if (viewAnchor == null) {
            return;
        }
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_redpackage_after_invitation, null, false);
        TextView tvGetRedPackage = view.findViewById(R.id.tv_get_redpackage);
        TextView tvMoney = view.findViewById(R.id.tv_money);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setAnimationStyle(R.style.Rising);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.7f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new ViewUtil.PopDismissListener(mActivity));
        tvMoney.setText("1");
        tvGetRedPackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   CommonUtil.getInstance().updateUserInfo(null);
                updateUserInfo(null);
                popupWindow.dismiss();
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();

            }
        });

    }

    public void updateUserInfo(final Action1<UserEntity> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null)
                            action1.call(null);

                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        UserEntity userEntity = baseMessage.getData(UserEntity.class);
                        if (userEntity != null) {
                            DataUtil.getInstance().setUserEntity(userEntity);
                        }
                        if (action1 != null)
                            action1.call(userEntity);
                    }
                });
    }


    /**
     * 新手任务对话框中，注册账号并登录得红包，这里判断是否已经领取过了，如果领取过了就不显示，不然就显示
     *
     * @param obj ,Context对象
     */
    public void isShowRedPackages(Context obj) {
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
        if (((userEntity.getNewbie_task_status() & 16) == 0) && userEntity.getIs_new() == 1) {
            showRedPackage(obj);

        }

    }

    /**
     * @return 是否显示红包
     */
    public void isShowRedPackage() {
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
        if (userEntity == null) {
            CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                @Override
                public void call(UserEntity result) {
                    if (result != null) {
                        userEntity = result;
                        showRedPackageNext();
                    }
                }
            });
        } else {
            showRedPackageNext();
        }
    }

    private void showRedPackageNext() {
        if (SpUtils.getFirst("first" + userEntity.getId())) {//不是第一次进入APP
            return;
        }
        SpUtils.saveFirst("first" + userEntity.getId(), true);//第一次登录成功后保存起来，下次进来就不再弹新人红包
        if (((userEntity.getNewbie_task_status() & 16) == 0) && userEntity.getIs_new() == 1) {
            showRedPackage(getContext());
        }
    }

    /**
     * 初始化选项卡
     *
     * @param context 上下文参数
     */
    @SuppressLint("InflateParams")
    private void initTitleCardLayout(final Context context) {
//        titleCardLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.view_float_title_card, null);
        doIt = titleCardLayout.findViewById(R.id.do_it_text);
        willStart = titleCardLayout.findViewById(R.id.will_start_text);
        doItLine = titleCardLayout.findViewById(R.id.do_it_every_day_line);
        lines = titleCardLayout.findViewById(R.id.but_will_start);
        int lineX = (G.WIDTH / 6) - (getViewWidth(doItLine) / 2);
        lines.setX(lineX);
        ViewGroup.LayoutParams layoutParams = lines.getLayoutParams();
        layoutParams.width = G.WIDTH - (lineX * 2);
        doIt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mViewPager != null) {
                    mViewPager.setCurrentItem(0);
                }
                toDayClick();
            }
        });
        willStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mViewPager != null) {
                    mViewPager.setCurrentItem(1);
                }
                willStartClick();
            }
        });
//        ((ViewGroup) activity.getWindow().getDecorView()).addView(titleCardLayout);
        titleCardLayout.setVisibility(View.GONE);
    }

    /**
     * 每日必做按钮事件回调
     */
    private void toDayClick() {
        doIt.setTextColor(getResources().getColor(R.color.blue_34a6e7));
        willStart.setTextColor(getResources().getColor(R.color.black_444444));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            TransitionManager.beginDelayedTransition(titleCardLayout, new ChangeBounds());
        }
        lines.setGravity(Gravity.START);
    }

    /**
     * 即将开始按钮事件回调
     */
    private void willStartClick() {
        doIt.setTextColor(getResources().getColor(R.color.black_444444));
        willStart.setTextColor(getResources().getColor(R.color.blue_34a6e7));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            TransitionManager.beginDelayedTransition(titleCardLayout, new ChangeBounds());
        }
        lines.setGravity(Gravity.END);
    }

    /**
     * 获取控件宽度
     *
     * @param view 视图控件
     * @return 返回视图控件的宽度
     */
    private int getViewWidth(View view) {
        int Kw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int Kh = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(Kw, Kh);
        return view.getMeasuredWidth();
    }

    @Override
    public int getLayoutId() {
        return R.layout.homepage_act_layout;
    }

    @Override
    public void onViewCreated() {
        activity = getActivity();
        showPDialog();
        initView();
        initListener();
        initTitleCardLayout(activity.getApplicationContext());
        TestUtil.testChange(activity, test_change);
        TestUtil.testChangeUser(activity, test_change_user);
        if (pagePresenter != null) {
            initData();
        }
        //每次进入主页都刷新一下url配置信息
        CommonUtil.getInstance().initUrlConfigByNet(null, null);
        if(TestUtil.isLTVersion3_4_5())//3.4.5以前版本才调用下面的方法
            isShowRedPackage();
    }


    //banner的高度
    private int bannerHeight = G.WIDTH * 17 / 40;
    public void initView() {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        DaggerSmallSheepComponent.builder()
                .netComponent(SheepApp.getInstance().getNetComponent())
                .smallSheepModule(new SmallSheepModule(this))
                .tryMakeMoneyModule(new TryMakeMoneyModule(this))
                .build()
                .inject(this);
        recyclerInitView();
        ViewGroup.LayoutParams bannerLayoutParams = banner.getLayoutParams();
        bannerHeight = G.WIDTH * 17 / 40;
        bannerLayoutParams.height = bannerHeight;//图片比例发生变化 ：306*720
//        bannerLayoutParams.height = G.WIDTH * 25 / 72;
        banner.setLayoutParams(bannerLayoutParams);

        /**
         * tablayout
         */
        mAdapter = new AdpTryMakemoney(getChildFragmentManager(), activity);
        FgtHomeTaskReleaseList firstItem = FgtHomeTaskReleaseList.newInstance(0, "is_hot");
        FgtHomeTaskReleaseList secondItem = FgtHomeTaskReleaseList.newInstance(1, "about_to_begin");
        firstItem.setViewPager(mViewPager);
        firstItem.setSmartRefreshLayout(refresh);
        secondItem.setViewPager(mViewPager);
        secondItem.setSmartRefreshLayout(refresh);
        mAdapter.add(firstItem, "每日必做");
        mAdapter.add(secondItem, "即将开始");

        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(mAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    toDayClick();
                } else if (position == 1) {
                    willStartClick();
                }
                curPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        CommonUtil.getInstance().reflex(tabLayout, activity);
        setAnimation(ivDuty);
        //只显示图片并且充满的homeList
        fullHomeList.clear();
        full_home_list_rv.setHasFixedSize(true);
        full_home_list_rv.setNestedScrollingEnabled(false);
        full_home_list_rv.setLayoutManager(new LinearLayoutManager(activity));
        full_home_list_rv.setAdapter(new AdbCommonRecycler<HomeListEntity>(activity, fullHomeList) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_image_full_home_list;
            }

            @Override
            public void convert(ViewHolder holder, final HomeListEntity item) {
                ImageView imageView = holder.getView(R.id.image);
                GlideImageLoader.setImage(imageView, item.getIcon());
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CommonUtil.getInstance().goWhere(activity, item, "首页");
                    }
                });
            }
        });
        //上面的搜索
        ViewUtil.setVisibility(home_search_msg_tv, false);
    }

    private int curPosition = 0;

    /**
     * 给请红包浮标设置动画，达到左右晃动
     *
     * @param imageView 设置动画的imageview
     */
    private void setAnimation(ImageView imageView) {
        TranslateAnimation animation = new TranslateAnimation(0, -5, 0, 0);
        animation.setInterpolator(new OvershootInterpolator());
        animation.setDuration(150);
        animation.setRepeatCount(Integer.MAX_VALUE);//根据产品要求，要一直晃动
        animation.setRepeatMode(Animation.REVERSE);
        if (imageView != null)
            imageView.startAnimation(animation);
    }

    private void loadUserInfo() {

        if (myPrice == null || userEntity == null) {
            return;
        }
        ViewUtil.setText(nameTv, userEntity.getNickname());
        ViewUtil.setText(sheepNumTv, String.format(Locale.CHINA, "绵羊号：%s", userEntity.getInvitation_code()));
        if (ConfigUtil.isSmallDebug()) {
            sheepNumTv.append("\n邀请人：");
            sheepNumTv.append(userEntity.getParent_code());
        }
        ViewUtil.setText(myPrice, String.format(Locale.CHINA, "%s\u0020元", userEntity.getBalance()));
        GlideImageLoader.setAvatar(iconImgIv, userEntity.getAvatar(), Color.argb(128, 255, 255, 255));

    }

    @SuppressLint("ClickableViewAccessibility")
    public void initListener() {
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int x, int y, int oldX, int oldY) {
                listTitle.getLocationInWindow(locate);
                if (locate[1] < 0 && titleCardLayout.getVisibility() == View.GONE) {
                    titleCardLayout.setVisibility(View.VISIBLE);
                } else if (locate[1] > 20 && titleCardLayout.getVisibility() == View.VISIBLE) {
                    titleCardLayout.setVisibility(View.GONE);
                }
                //设置搜索框颜色变化
//                float ratio = Math.min(bannerHeight, y) * 1.0f / bannerHeight;
//                to_search_but_rl.setBackgroundColor(Color.argb((int) (ratio * 255), 255, 255, 255));
//                float colorRatio = 1 - ratio * 0.26f;
//                Drawable bg = to_search_but.getBackground();
//                if(bg instanceof GradientDrawable){
//                    GradientDrawable drawable = (GradientDrawable) bg;
//                    drawable.setColor(Color.argb(216, (int) (colorRatio * 255), (int) (colorRatio * 255), (int) (colorRatio * 255)));
//                }
//                int[] minPerS = {102, 153};
//                for (int i = 0; i < to_search_but.getChildCount(); i++) {
//                    int minPer = minPerS[i % minPerS.length];
//                    int per = (int) ((255 - minPer) * ratio + minPer);
//                    int textColor = Color.argb(255, per, per, per);
//                    View childView = to_search_but.getChildAt(i);
//                    if(childView instanceof TextView){
//                        ((TextView) childView).setTextColor(textColor);
//                    }
//                }
//                LogUtil.println("FgtSmallSheep", "onScrollChange", x, y, oldX, oldY, locate[0], locate[1]);
            }
        });
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (upview1 != null) {
                            //开始滚动
                            upview1.stopFlipping();
                        }
                        if (homepageItemNoticeMv != null) {
                            //开始滚动
                            homepageItemNoticeMv.stopFlipping();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    default:
                        if (upview1 != null) {
                            //开始滚动
                            upview1.startFlipping();
                        }
                        if (homepageItemNoticeMv != null) {
                            //开始滚动
                            homepageItemNoticeMv.startFlipping();
                        }
                        break;
                }
                return false;
            }
        });

        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                FgtHomeTaskReleaseList item = (FgtHomeTaskReleaseList) mAdapter.getItem(curPosition);
                if (item == null) {
                    notifyDataSetChanged();
                    return;
                }
                item.loadMoreData();
                notifyDataSetChanged();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        RefreshUtil.newInstance().publicParameterLoadMore(refresh, activity);
    }

    private void notifyDataSetChanged() {
        if (refresh != null) {
            refresh.finishRefresh();
            refresh.finishLoadMore();
        }
    }

    /**
     * 初始化数据
     */
    public void initData() {
        //用户信息
        userEntity = DataUtil.getInstance().getUserEntity();
        if (userEntity != null) {
            loadUserInfo();
        }
        //任务
//        List<TaskReleaseEty> cacheTaskReleaseEtyList = DataUtil.getInstance().getCacheList(ApiKey.release_task, TaskReleaseEty.class);
//        if (cacheTaskReleaseEtyList != null) {
//            releaseEtyLists.addAll(cacheTaskReleaseEtyList);
//            mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
//        }


        //实时动态
        List<MoreDataEntity> cacheMoreDataEtyList = DataUtil.getInstance().getCacheList(ApiKey.award_detail, MoreDataEntity.class);
        if (!ListUtil.isEmpty(cacheMoreDataEtyList)) {
            invite(cacheMoreDataEtyList);
        }

        //公告
        List<BulletinEnty> cacheBulletinEtyList = DataUtil.getInstance().getCacheList(ApiKey.bulletin, BulletinEnty.class);
        if (ListUtil.isEmpty(cacheBulletinEtyList)) {
            homepageItemNoticeLayout.setVisibility(View.GONE);
        } else {
            bulletinEntyLists.clear();
            bulletinEntyLists.addAll(cacheBulletinEtyList);
            inviteNotice(bulletinEntyLists);
        }
        //轮播
        List<SlideshowEty> cacheSlideshowEtyList = DataUtil.getInstance().getCacheList(ApiKey.slideshow, SlideshowEty.class);
        if (ListUtil.isEmpty(cacheSlideshowEtyList)) {
            banner.setVisibility(View.GONE);
        } else {
            for (SlideshowEty slideshowEty : cacheSlideshowEtyList) {
                slideshowEtyLists.add(slideshowEty);
                slideshowTitleList.add(slideshowEty.getTitle());
            }
            bindBanner();
        }
        //首页list
        List<HomeListEntity> cacheHomeListEtyList = DataUtil.getInstance().getCacheList(ApiKey.home_list, HomeListEntity.class);
        if (ListUtil.isEmpty(cacheHomeListEtyList)) {
            home_list_gridview_layout.setVisibility(View.GONE);
            full_home_list_rv.setVisibility(View.GONE);
        } else {
            home_list_gridview_layout.setVisibility(View.VISIBLE);
            fullHomeList.clear();
            CommonUtil.getInstance().splitHomeList(cacheHomeListEtyList, homeListEntitys, fullHomeList);
            full_home_list_rv.setVisibility(fullHomeList.isEmpty() ? View.GONE : View.VISIBLE);
            boolean isShowQB = false;
            boolean isShowMd = false;
            for (int i = 0; i < homeListEntitys.size(); i++) {
                /*if (i < 4) {
                    homeListEntitysGridview.add(homeListEntitys.get(i));
                } else {
                    homeListEntitysListview.add(homeListEntitys.get(i));
                }*/
                homeListEntitysGridview.add(homeListEntitys.get(i));
                if (homeListEntitys.get(i).getJump().equals("6")) {//6Q币充值
                    isShowQB = !isShowQB;
                }
                if (homeListEntitys.get(i).getJump().equals("14")) {//幂动科技
                    isShowMd = !isShowMd;
                }
            }
            addNewTask();
            SheepApp.getInstance().setShowQB(isShowQB);
            SheepApp.getInstance().setShowMidong(isShowMd);
            full_home_list_rv.getAdapter().notifyDataSetChanged();
            adpHomeListGrideview.notifyDataSetChanged();
            adpHomeListListview.notifyDataSetChanged();
            home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
        }
        refreshData();
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                if (result != 0) {//无网络
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
                notifyDataSetChanged();
            }
        });
        getUnReadMessageCounts();
        if (upview1 != null) {
            //停止滚动
            upview1.stopFlipping();
            upview1.startFlipping();
        }
        if (homepageItemNoticeMv != null) {
            //停止滚动
            homepageItemNoticeMv.stopFlipping();
            homepageItemNoticeMv.startFlipping();
        }
        if (onResumeCount > 0 || userEntity == null)//非第一次才更新用户信息
            pagePresenter.getUserInfo();

        if (views.size() < 1) {
            pagePresenter.getAwardDetail();
        }
        refreshTaskList();//任务
        pagePresenter.bulletin(null);//公告
        pagePresenter.slideshow(null);//轮播
        pagePresenter.homeList();//首页list

        CommonUtil.getInstance().getUserNoDoingTaskMoney(new Action1<BaseMessage>() {
            @Override
            public void call(BaseMessage o) {

                if (o != null) {
                    CashAwarsEntity cashAwarsEntity = o.getData(CashAwarsEntity.class);
                    if (cashAwarsEntity != null) {

                        String award = String.format(activity.getResources().getString(R.string.homepage_award), NumberFormatUtils.retainMost2(cashAwarsEntity.getAward()));
                        String cash = String.format(activity.getResources().getString(R.string.homepage_cash), NumberFormatUtils.retainMost2(cashAwarsEntity.getCash()));
                        String welfare = String.format(activity.getResources().getString(R.string.homepage_welfare), NumberFormatUtils.retainMost2(cashAwarsEntity.getWelfare()));
                        homepage_item_get_award_name_tv.setText(award);
                        homepage_item_money_tv.setText(cash);
                        homepage_item_juan_tv.setText(welfare);
                    }
                }
            }
        });
        if (!isFirst) {
            for (int i = 0; i < mAdapter.getCount(); i++) {
                FgtHomeTaskReleaseList item = (FgtHomeTaskReleaseList) mAdapter.getItem(i);
                item.refreshData();
            }
        }
        isFirst = false;
    }

    private boolean isFirst = true;

    /**
     * recyclerview
     */
    private void recyclerInitView() {
        recyclerview.setLayoutManager(new LinearLayoutManager(activity));
        //recyclerView 解决滑动不流畅问题
        recyclerview.setHasFixedSize(true);
        recyclerview.setNestedScrollingEnabled(false);
        tryMakeMoneyAdp = new TryMakeMoneyAdp(activity, 1);//1代表来自主页
        for (int i = 0; i < LIST_COUNT; i++) {
            tryMakeMoneyAdp.add(NULL);
        }
        tryMakeMoneyAdp.addType(1);
        tryMakeMoneyAdp.setIs_succession(3);
        tryMakeMoneyAdp.addPresenter(tryMakeMoneyPresenter);
        recyclerview.setAdapter(tryMakeMoneyAdp);

        adpHomeListListview = new AdpHomeListListview(homeListEntitysListview, activity);
        adpHomeListGrideview = new AdpHomeListGrideview(homeListEntitysGridview, activity);
        home_list_gridview_listview.setAdapter(adpHomeListListview);
        home_list_gridview_gv.setAdapter(adpHomeListGrideview);

        home_list_gridview_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeListEntity homeListEntity = ListUtil.getItem(homeListEntitysGridview, position);
                if (homeListEntity == null) {
                    return;
                }
                UMConfigUtils.IdEvent.HOME_LIST.commit(homeListEntity.getId());
                if ("-2".equals(homeListEntity.getJump())) {
                    clickCount += 1;
                    setValueList(!homeListEntity.isSelect());
                } else {
                    CommonUtil.getInstance()
                            .goWhere(activity, homeListEntity, "首页");
                }
            }
        });
    }

    private void refreshTaskList() {
        tryMakeMoneyPresenter.returnTask(is_succession, show_game_task);
        RequestParamEty parameEty = new RequestParamEty();
        parameEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(1,
                                100,
                                SheepApp.getInstance().getConnectAddress().getPlatForm(),
                                1,
                                0,
                                0,
                                "-1",
                                3));
//        tryMakeMoneyPresenter.releaseTask(parameEty);
    }


    @OnClick({R.id.recharge, R.id.withdrawal, R.id.view_rob_duty,
            R.id.newbie_task, R.id.icon_img_iv, R.id.user_layout,
            R.id.homepage_item_money_tv
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.homepage_item_money_tv:
                Jump2View.getInstance().goTryplayView(activity, null);
                break;
            case R.id.withdrawal://提现
                Jump2View.getInstance().tryGoWithdrawal(activity, userEntity);
                break;
            case R.id.newbie_task://新手任务
                DialogNewbieTaskList.tryShowDialog(activity);
                NEWBIE_TASK.onEvent();
                break;
            case R.id.icon_img_iv://头像
                if (TestUtil.isTest()) {
                    TestUtil.test(activity);
                } else
                    Jump2View.getInstance().goPersonnalCenterView(activity, null);
                break;
            case R.id.user_layout://个人信息
                Jump2View.getInstance().goPersonnalCenterView(activity, null);
                break;
            case R.id.recharge://充值
                Jump2View.getInstance().goRechargeAct(activity, "首页");
                break;
            case R.id.view_rob_duty://抢任务弹框
                CommonUtil.getInstance().robTask(new Action1<RobTask>() {
                    @Override
                    public void call(RobTask robTask) {
                        if (robTask != null) {
                            DataUtil.putAsInt(DataKey.KEY_ORDER, robTask.getOrder());
                            try {
                                ViewUtil.newInstance().showRobDutyDialog(activity, robTask);
                            } catch (Exception e) {
                                e.printStackTrace();
                                G.showToast(e.getMessage());
                            }
                        } else {
                            G.showToast("任务已被抢光！请实时关注任务发布！");
                        }
                    }
                });
                break;
        }
    }

    @Override
    public void updateData2View(Object o) {
        if (o == null) {
            return;
        }
        BaseMessage baseMessage = (BaseMessage) o;
        userEntity = baseMessage.getData(UserEntity.class);
        if (userEntity == null) {
            return;
        }
        DataUtil.getInstance().setUserEntity(userEntity);
        mHandler.sendEmptyMessage(WHAT_LOAD_USER_INFO);
    }

    @Override
    public void failData2View(Object o) {
        G.showToast("网络错误");

    }

    @Override
    public void acceptedTaskUpdataView(Object o) {
        refreshTaskList();
    }

    @Override
    public void failAcceptedTask2View(Object o) {

    }

    @Override
    public void giveUpTaskSuccesView(Object object) {
        G.showToast("取消任务成功");
        CommonUtil.getInstance().updateAutoCheck(null);
        refreshTaskList();
        FgtHomeTaskReleaseList item = (FgtHomeTaskReleaseList) mAdapter.getItem(0);//因为放弃了任务，所以刷新可以接收的任务列表
        item.refreshData();
    }

    @Override
    public void giveUpTaskFailView(Object o) {

    }

    private int is_succession = 3;//所有
    private int show_game_task = 1;//包含游戏任务

    @Override
    public void returnTaskTaskUpdateView(Object object) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.new_run_task(is_succession, show_game_task));
        if (isNewData) {
            BaseMessage baseMessage = (BaseMessage) object;
            allTaskAcceptedTaskList = baseMessage.getDataList(TaskAcceptedEty.class);
            CommonUtil.getInstance().reloadAutoTaskList(allTaskAcceptedTaskList);
        } else {
            allTaskAcceptedTaskList.clear();
        }
        mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
    }

    @Override
    public void failReturnTask2View(Object o) {

        try {
            BaseMessage baseMessage = (BaseMessage) o;
            switch (baseMessage.getCode()) {
                case 300://未查询到正在运行的任务
//                    G.showToast(" 未查询到正在运行的任务！");
                    break;
                default:
                    G.showToast(" 网络错误！");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            G.showToast(" 网络错误！");
        }
        allTaskAcceptedTaskList.clear();
        mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
    }

    @Override
    public void releaseTaskTaskUpdateView(BaseMessage baseMessage, int about_to_begin) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.release_task);
        if (isNewData) {
            List<Release_task> releaseEtyList = baseMessage.getDataList(Release_task.class);
            if (releaseEtyList != null) {
                releaseEtyLists = releaseEtyList;
                mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
            }
        }
    }

    @Override
    public void failReleaseTask2View(BaseMessage baseMessage, int about_to_begin) {
    }

    @Override
    public void showMore(final List<MoreDataEntity> loginEty) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                invite(loginEty);
            }
        });


    }

    /**
     * 公告和轮播
     *
     * @param baseMessage
     */
    @Override
    public void failSlideshow(BaseMessage baseMessage) {

    }

    @Override
    public void successSlideshow(BaseMessage baseMessage) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.slideshow);
        if (isNewData) {
            List<SlideshowEty> slideshowEtyList = baseMessage.getDataList(SlideshowEty.class);
            if (ListUtil.isEmpty(slideshowEtyList)) {
                banner.setVisibility(View.GONE);
            } else {
                slideshowEtyLists.clear();
                slideshowTitleList.clear();
                for (SlideshowEty slideshowEty : slideshowEtyList) {
                    slideshowEtyLists.add(slideshowEty);
                    slideshowTitleList.add(slideshowEty.getTitle());
                }
                bindBanner();
            }
        }
    }

    @Override
    public void failbulletin(BaseMessage baseMessage) {

    }

    @Override
    public void successbulletin(BaseMessage baseMessage) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.bulletin);
        if (isNewData) {
            List<BulletinEnty> bulletinEntyList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), BulletinEnty.class);
            if (ListUtil.isEmpty(bulletinEntyList)) {
                homepageItemNoticeLayout.setVisibility(View.GONE);
            } else {
                bulletinEntyLists.clear();
                bulletinEntyLists.addAll(bulletinEntyList);
                inviteNotice(bulletinEntyLists);
            }
        }
    }

    @Override
    public void successhomeList(BaseMessage baseMessage) {
        checkAndInitView();
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.home_list);
        if (isNewData) {
            List<HomeListEntity> homeListEntityList = baseMessage.getDataList(HomeListEntity.class);
            if (ListUtil.isEmpty(homeListEntityList)) {
                home_list_gridview_layout.setVisibility(View.GONE);
                full_home_list_rv.setVisibility(View.GONE);
            } else {
                home_list_gridview_layout.setVisibility(View.VISIBLE);
                homeListEntitys.clear();
                homeListEntitysGridview.clear();
                homeListEntitysListview.clear();
                fullHomeList.clear();
                CommonUtil.getInstance().splitHomeList(homeListEntityList, homeListEntitys, fullHomeList);
                full_home_list_rv.setVisibility(fullHomeList.isEmpty() ? View.GONE : View.VISIBLE);
                boolean isShowQB = false;
                boolean isShowMd = false;
                for (int i = 0; i < homeListEntitys.size(); i++) {
//                    if (i < 4) {
//                        homeListEntitysGridview.add(homeListEntitys.get(i));
//                    } else {
//                        homeListEntitysListview.add(homeListEntitys.get(i));
//                    }
                    homeListEntitysGridview.add(homeListEntitys.get(i));
                    if (homeListEntitys.get(i).getJump().equals("6")) {//6Q币充值
                        isShowQB = !isShowQB;
                    }
                    if (homeListEntitys.get(i).getJump().equals("14")) {//幂动科技
                        isShowMd = !isShowMd;
                    }
                }
                addNewTask();
                SheepApp.getInstance().setShowQB(isShowQB);
                SheepApp.getInstance().setShowMidong(isShowMd);
                ViewUtil.notifyDataSetChanged(full_home_list_rv);
                adpHomeListGrideview.notifyDataSetChanged();
                adpHomeListListview.notifyDataSetChanged();
                home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
            }
        }
    }

    private void checkAndInitView() {
        if (recyclerview == null) {
            if (unbinder != null) {
                try {
                    unbinder.unbind();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                unbinder = null;
            }
            unbinder = ButterKnife.bind(this, getView());
        }
    }

    @Override
    public void failhomeList(BaseMessage baseMessage) {
        checkAndInitView();
        if(homeListEntitys.isEmpty() && fullHomeList.isEmpty())
            home_list_gridview_layout.setVisibility(View.GONE);

    }

    private int onResumeCount = 0;

    @Override
    public void onResume() {
        super.onResume();
        UserEntity result = DataUtil.getInstance().getUserEntity();
        if (result == null) {
            CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
                @Override
                public void call(UserEntity item) {
                    if (item != null) {
                        userEntity = item;
                        loadUserInfo();
                    }
                }
            });
        } else {
            userEntity = result;
            loadUserInfo();
        }
        if (onResumeCount > 0)
            refreshTaskList();
        onResumeCount++;
        setAnimation(ivDuty);
    }


    @Override
    public void onPause() {
        if (titleCardLayout != null) {
            titleCardLayout.setVisibility(View.GONE);
        }
        super.onPause();
        if (upview1 != null) {
            //停止滚动
            upview1.stopFlipping();
        }
        if (homepageItemNoticeMv != null) {
            //停止滚动
            homepageItemNoticeMv.stopFlipping();
        }
    }

    private void invite(final List<MoreDataEntity> moreDataEntityList) {
        views.clear();
        upview1.removeAllViews();
        for (MoreDataEntity entity : moreDataEntityList) {
            StringBuilder sb = new StringBuilder();
            sb.append(TimeStamp2Date(entity.getTime())).append("   ");
            sb.append(entity.getName()).append("   ");
            sb.append(entity.getDesc());
            TextView moreView = (TextView) LayoutInflater.from(activity).inflate(R.layout.x_item_view, null);
            moreView.setText(sb.toString());
            views.add(moreView);
            upview1.addView(moreView);
        }
//        upview1.setEasyViews(views);
        if (!upview1.isAutoStart()) {
            upview1.stopFlipping();
            upview1.startFlipping();
        }


    }


    public String TimeStamp2Date(long timestampString) {
        String formats = "yyyy-MM-dd HH:mm:ss";
        Long timestamp = timestampString * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case ONFRESH_FGT_FAMLLSHEEP:
                mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
                break;
            case FGT_SHEEP_SHOW_NEW_USER_HONG_BAO:
                mHandler.sendEmptyMessage(WHAT_TRY_SHOW_HB);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        userEntity = DataUtil.getInstance().getUserEntity();
        if (userEntity != null) {
            loadUserInfo();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    private void bindBanner() {
        //结束轮播
        banner.stopAutoPlay();
        banner.setVisibility(View.VISIBLE);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                try {
                    if (o instanceof SlideshowEty && activity != null && !activity.isDestroyed())
                        Glide.with(context).load(((SlideshowEty) o).getUrl()).apply(new RequestOptions().dontAnimate()).into(imageView);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        })
                .setDelayTime(4000)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                //设置图片集合
                .setImages(slideshowEtyLists).setBannerTitles(slideshowTitleList)
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int i) {
                        try {
                            CommonUtil.getInstance().clickBanner(activity, i, slideshowEtyLists);
                        } catch (Exception e) {
                            G.showToast(e.getMessage());
                        }
                    }
                });

        //banner设置方法全部调用完毕时最后调用
        banner.start();
//        //设置banner样式
//        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
//        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader());
//        //设置图片集合
//        banner.setImages(images);
//        //设置banner动画效果
//        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
//        //设置自动轮播，默认为true
//        banner.isAutoPlay(true);
//        //设置轮播时间
//        banner.setDelayTime(1500);
//        //设置指示器位置（当banner模式中有指示器时）
//        banner.setIndicatorGravity(BannerConfig.CENTER);
//        //banner设置方法全部调用完毕时最后调用
//        banner.start();
    }

    /**
     * 公共
     */
    private void inviteNotice(final List<BulletinEnty> bulletinEntyList) {
        homepageItemNoticeLayout.setVisibility(View.GONE);
        homepageItemNoticeMv.removeAllViews();
        for (final BulletinEnty entity : bulletinEntyList) {
            StringBuilder sb = new StringBuilder();
            sb.append(entity.getContent()).append("   ");
            TextView moreView = (TextView) LayoutInflater.from(activity).inflate(R.layout.x_item_view, null);
            moreView.setText(sb.toString());

            moreView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    onClickNotice(entity);
                }
            });
            homepageItemNoticeMv.addView(moreView);
        }
        if (!homepageItemNoticeMv.isAutoStart()) {
            homepageItemNoticeMv.stopFlipping();
            homepageItemNoticeMv.startFlipping();
        }

    }

    /**
     * 点击一条公告
     */
    private void onClickNotice(BulletinEnty item) {
        switch (item.getJumpType()) {// 跳转类型:11,任务 98,内部h5 99,外部h5
            case 11:
                Jump2View.getInstance().goTaskDetailView(activity, NumberFormatUtils.parseInteger(item.getJumpValue()));
                break;
            case 98:
                Jump2View.getInstance().goWeb(activity, item.getJumpValue(), null);
                break;
            case 99:
                Jump2View.getInstance().goWeb(activity, item.getJumpValue());
                break;
            case 14://幂动科技
                Jump2View.getInstance().goMiDong(activity, null);
                break;
            case 15://小米游戏列表
                Jump2View.getInstance().goXiaomiGameList(activity, null);
                break;
        }
    }

    /**
     * 提示用户开启推送通知权限
     * 1）只提示一次，如果用户取消，以后都不在提示
     */
    private void showPDialog() {
        boolean isShowDialog = DataUtil.getAsBoolean("isShowDialog", true);
        if (isShowDialog && !NotificationManagerCompat.from(activity).areNotificationsEnabled()) {//没有开启通知权限
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("提示");
            builder.setMessage("是否开启推送?");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DataUtil.putAsBoolean("isShowDialog", false);
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    NotificationsUtils.goToNotificationSetting(SheepApp.getInstance());
                }
            });
            builder.show();
        }

    }

    /**
     * 邀请成功后在个人资料显示领红包弹窗
     */
    public void showRedPackage(Context context) {
        Activity mActivity = (Activity) context;
        View viewAnchor = LayoutInflater.from(context).inflate(R.layout.homepage_act_layout, null, false);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_redpackage_after_invitation, null, false);
        TextView tvGetRedPackage = view.findViewById(R.id.tv_get_redpackage);
        TextView tvMoney = view.findViewById(R.id.tv_money);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        TextView tvNew = view.findViewById(R.id.tv_flag1);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setAnimationStyle(R.style.Rising);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.7f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new PopDismissListener(mActivity));
        tvMoney.setText("1.8");
        tvNew.setText("新人红包");
        tvGetRedPackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                getRedPackage(popupWindow);

            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();


            }
        });

    }

    /**
     * popwindow消失监听类，消失恢复window透明度
     */
    class PopDismissListener implements PopupWindow.OnDismissListener {
        Activity mActivity;

        public PopDismissListener(Activity activity) {
            mActivity = activity;
        }

        @Override
        public void onDismiss() {
            backgroundAlpha(1f, mActivity);
            if (SpUtils.getFirst("first_invitation" + userEntity.getId())) {//不是第一次进入APP
                return;
            }
            SpUtils.saveFirst("first_invitation" + userEntity.getId(), true);//第一次登录成功后保存起来，下次进来就不再弹新人红包
            if (((userEntity.getNewbie_task_status() & 16) == 0) && userEntity.getIs_new() == 1) {
                isShowRedPackageWithCode();//邀请红包
            }

        }
    }

    /**
     * @param bgAlpha  ，透明度值
     * @param activity 恢复透明度
     */
    public static void backgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 兑换红包
     *
     * @param popupWindow
     */
    public void getRedPackage(final PopupWindow popupWindow) {
        SheepApp.getInstance().getNetComponent().getApiService().getNewRedPackage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                        CommonUtil.getInstance().updateUserInfo(null);
                    }
                });
    }

    /**
     * 新手任务
     */
    private void addNewTask() {

        if (CommonUtil.getInstance().addNewTask(activity, userEntity) && homeListEntitysGridview != null) {
            HomeListEntity homeListEntityNewTask = new HomeListEntity();
            homeListEntityNewTask.setTitle("新手任务");
            homeListEntityNewTask.setDesc("新手任务");
            homeListEntityNewTask.setJump("-1");
            homeListEntityNewTask.setIcon("http://cdngame.kuaifazs.com/homepage_xinshourw.png");
            homeListEntitys.add(0, homeListEntityNewTask);
        }
        if (homeListEntitys.size() > 8) {
            HomeListEntity homeListEntity = new HomeListEntity();
            homeListEntity.setTitle("更多");
            homeListEntity.setDesc("查看更多");
            homeListEntity.setJump("-2");
            homeListEntity.setIcon("http://cdngame.kuaifazs.com/homepage_chakangd.png");
            homeListEntitys.add(7, homeListEntity);
        }
        setValueList(false);
    }

    private void setValueList(boolean flag) {
        homeListEntitysGridview.clear();
        for (int i = 0; i < homeListEntitys.size(); i++) {
            if (flag) {
                homeListEntitysGridview.add(homeListEntitys.get(i));
            } else {
                if (i < 8) {
                    homeListEntitysGridview.add(homeListEntitys.get(i));
                }
            }
        }
        if (homeListEntitysGridview.size() > 8) {
            HomeListEntity homeListEntity = new HomeListEntity();
            homeListEntity.setJump("-2");
            homeListEntity.setSelect(flag);
            if (flag) {
                homeListEntity.setTitle("收起");
                homeListEntity.setDesc("收起模块");
                homeListEntity.setIcon("http://cdngame.kuaifazs.com/homepage_chakangd_click.png");
            } else {
                homeListEntity.setTitle("更多");
                homeListEntity.setDesc("查看更多");
                homeListEntity.setIcon("http://cdngame.kuaifazs.com/homepage_chakangd.png");
            }
            homeListEntitysGridview.set(7, homeListEntity);
        }
        /* 为了避免第一次点击时网络图片未加载到本地导致UI混乱,第一次点击不执行此动画,转而使用View自带的变换动画 */
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && clickCount > 1) {
//            TransitionManager.beginDelayedTransition(home_list_gridview_gv, new ChangeBounds());
//        }
        adpHomeListGrideview.notifyDataSetChanged();
    }
    @BindView(R.id.home_search_msg_tv)
    TextView home_search_msg_tv;
    /**
     * 获取是否有未读消息并更新图标
     */
    private void getUnReadMessageCounts() {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getMessageUnReadNum(DataUtil.getInstance().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        MessageUnReadEntity entity = baseMessage.getData(MessageUnReadEntity.class);
                        if (entity != null && entity.getNum() > 0) {
                            ViewUtil.setVisibility(home_search_msg_tv, true);
                            ViewUtil.setText(home_search_msg_tv, entity.getNum());
                        } else {
                            ViewUtil.setVisibility(home_search_msg_tv, false);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                    }
                });

    }
}
