package com.kfzs.duanduan.fragment;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
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.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.google.gson.Gson;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.react.ConfigUtil;
import com.kfzs.duanduan.react.SharedPreferences;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.kfzs.duanduan.utils.dlg.FormatAny;
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.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.BulletinEnty;
import com.sheep.gamegroup.model.entity.CashAwarsEntity;
import com.sheep.gamegroup.model.entity.Ext;
import com.sheep.gamegroup.model.entity.HomeListEntity;
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.RequestParameEty;
import com.sheep.gamegroup.model.entity.SlideshowEty;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.TaskReleaseEty;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.AutoTaskListUtil;
import com.sheep.gamegroup.model.util.EntityUtils;
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.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.NotificationsUtils;
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.gamegroup.view.fragment.FgtTryMakeMoney;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
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 rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

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

public class FgtSmallSheep extends BaseCompatFragment 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)
    SwipeRefreshLayout 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.bottom_line_text)
    TextView bottom_line_text;


    @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<TaskReleaseEty> 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> homeListEntitysGridview = new ArrayList<>();
    private List<HomeListEntity> homeListEntitysListview = new ArrayList<>();
    private AdpHomeListGrideview adpHomeListGrideview;
    private AdpHomeListListview adpHomeListListview;
    private TaskReleaseEty taskEty;
    private AdpTryMakemoney adpViewPagerDetail;

    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_UPDATE_VP_HEIGHT = 2;//刷新viewpager高度
    public static final int WHAT_TRY_SHOW_HB = 7;//尝试显示红包
    public Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            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();
                    checkAndInitView();
                    break;
                case WHAT_UPDATE_VP_HEIGHT:
                    FgtTryMakeMoney item = (FgtTryMakeMoney) adpViewPagerDetail.getItem(curPosition);
                    if (mViewPager == null || item == null) {
                        return;
                    }
                    int count = item.getDataCount();
                    ViewGroup.LayoutParams params = mViewPager.getLayoutParams();
                    params.height = count == 0 ? G.HEIGHT / 2 : (count * getResources().getDimensionPixelSize(R.dimen.content_padding_96) + getResources().getDimensionPixelSize(R.dimen.content_padding));
                    mViewPager.setLayoutParams(params);
                    break;
                case WHAT_TRY_SHOW_HB:
                    isShowRedPackages(activity);
                    break;
            }

        }
    };

    /**
     * @return 是否显示兑换邀请码红包
     */
    private void isShowRedPackageWithCode() {
        //  DataUtil.getInstance().是官方包吗();
        if (userEntity == null) {
            userEntity = DataUtil.getInstance().getUserEntity();
        }
        if (userEntity.getParent_code() != null) {
            return;
        } else {
            if (!userEntity.getParent_code().equals("") || (userEntity.getCreate_time_line() < 2) || (userEntity.getPackage_cate() == 1)) {

            } else {
                changeRedPackage(getActivity(), LayoutInflater.from(getContext()).inflate(R.layout.activity_main, 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();
                }
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

    }

    /**
     * 兑换红包
     *
     * @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.mContext) {
                    @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.activity_main, 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.get(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 (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());
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.homepage_act_layout);
        activity = getActivity();
        showPDialog();
        initView();
        initListener();
        TestUtil.testChange(activity, (TextView) getViewById(R.id.test_change));
        TestUtil.testChangeUser(activity, (TextView) getViewById(R.id.test_change_user));
        GlideImageLoader.setImage(bg_newbie_task, "http://cdngame.kuaifazs.com/bg_newbie_task.png");
        if (pagePresenter != null) {
            initData();
        }
        //每次进入主页都刷新一下url配置信息
        CommonUtil.getInstance().initUrlConfigByNet(null, null);
        isShowRedPackage();
        bottom_line_text.setText("我是有底线的，双击我回到顶部");
    }


    public void initView() {
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, mContentView);
        DaggerSmallSheepComponent.builder()
                .netComponent(SheepApp.getInstance().getNetComponent())
                .smallSheepModule(new SmallSheepModule(this))
                .tryMakeMoneyModule(new TryMakeMoneyModule(this))
                .build()
                .inject(this);
        recyclerInitView();
        LinearLayout.LayoutParams bannerLayoutParams = (LinearLayout.LayoutParams) banner.getLayoutParams();
        bannerLayoutParams.height = G.WIDTH * 25 / 72;
        banner.setLayoutParams(bannerLayoutParams);

        /**
         * tablayout
         */
        adpViewPagerDetail = new AdpTryMakemoney(getChildFragmentManager(), activity);
        adpViewPagerDetail.add(FgtTryMakeMoney.newInstance(0, "is_hot"), "每日必做");
        adpViewPagerDetail.add(FgtTryMakeMoney.newInstance(1, "about_to_begin"), "即将开始");

//        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(adpViewPagerDetail);

        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) {
                curPosition = position;
                mHandler.sendEmptyMessage(WHAT_UPDATE_VP_HEIGHT);//重新计算viewpager高度
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        CommonUtil.getInstance().reflex(tabLayout, activity);
        setAnimation(ivDuty);
    }

    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);
        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.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.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
                refresh.setRefreshing(false);
            }
        });

    }

    /**
     * 初始化数据
     */
    public void initData() {
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(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);
                }
            }
        });

        //用户信息
        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) {
                slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
                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);
        } else {
            home_list_gridview_layout.setVisibility(View.VISIBLE);
            homeListEntitys.addAll(cacheHomeListEtyList);
            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);
            adpHomeListGrideview.notifyDataSetChanged();
            adpHomeListListview.notifyDataSetChanged();
            home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
        }
        refreshData();
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(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);
                }
            }
        });
        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), FormatAny.getInstance().formatString(cashAwarsEntity.getAward() + ""));
                        String cash = String.format(activity.getResources().getString(R.string.homepage_cash), FormatAny.getInstance().formatString(cashAwarsEntity.getCash() + ""));
                        String welfare = String.format(activity.getResources().getString(R.string.homepage_welfare), FormatAny.getInstance().formatString(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 < adpViewPagerDetail.getCount(); i++) {
                FgtTryMakeMoney item = (FgtTryMakeMoney) adpViewPagerDetail.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())) {
                    setValueList(!homeListEntity.isSelect());
                } else {
                    CommonUtil.getInstance()
                            .goWhere(activity, homeListEntity, "首页");
                }
            }
        });
    }

    private void refreshTaskList() {
        tryMakeMoneyPresenter.returnTask(is_succession, show_game_task);
        RequestParameEty parameEty = new RequestParameEty();
        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.bottom_line
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            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://抢任务弹框
                ViewUtil.showRobDutyDialog(getActivity(), getView());
                break;
            case R.id.bottom_line://我是有底线的，双击我回到顶部
                scrollView.fullScroll(NestedScrollView.FOCUS_UP);
                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().setTAskEnty(null);
        refreshTaskList();
        FgtTryMakeMoney item = (FgtTryMakeMoney) adpViewPagerDetail.getItem(0);//因为放弃了任务，所以刷新可以接收的任务列表
        item.refreshData();
    }

    @Override
    public void giveUpTaskFailView(Object o) {

    }

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

    @Override
    public void returnTaskTaskUpdataView(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);
            AutoTaskListUtil.getInstance().loadList(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 releaseTaskTaskUpdataView(Object object) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.release_task);
        if (isNewData && object instanceof BaseMessage) {
            List<TaskReleaseEty> releaseEtyList = ((BaseMessage) object).getDataList(TaskReleaseEty.class);
            if (releaseEtyList != null) {
                releaseEtyLists = releaseEtyList;
                mHandler.sendEmptyMessage(WHAT_LOAD_RUN_TASK);
            }
        }
    }

    @Override
    public void failReleaseTask2View(Object o) {
    }

    @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) {
                    slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
                    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);
            } else {
                home_list_gridview_layout.setVisibility(View.VISIBLE);
                homeListEntitys.clear();
                homeListEntitysGridview.clear();
                homeListEntitysListview.clear();
                homeListEntitys.addAll(homeListEntityList);
                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);
                adpHomeListGrideview.notifyDataSetChanged();
                adpHomeListListview.notifyDataSetChanged();
                home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
            }
        }
    }

    private void checkAndInitView() {
        if (recyclerview == null)
            recyclerview = mContentView.findViewById(R.id.recyclerview);
        if (scrollView == null)
            scrollView = mContentView.findViewById(R.id.scrollView);
        if (home_list_gridview_layout == null)
            home_list_gridview_layout = mContentView.findViewById(R.id.home_list_gridview_layout);
        if (home_list_gridview_listview == null)
            home_list_gridview_listview = mContentView.findViewById(R.id.home_list_gridview_listview);
    }

    @Override
    public void failhomeList(BaseMessage baseMessage) {
        checkAndInitView();
        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() {
        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_REFRESH_H:
                mHandler.sendEmptyMessage(WHAT_UPDATE_VP_HEIGHT);
                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 View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        if (rootView != null)
            unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @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) {
                if (o instanceof SlideshowEty)
                    Glide.with(context).load(((SlideshowEty) o).getUrl()).apply(new RequestOptions().dontAnimate()).into(imageView);
            }
        })
                .setDelayTime(4000)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                //设置图片集合
                .setImages(slideshowEtyLists).setBannerTitles(slideshowTitleList)
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int i) {
                        clickBanner(i);
                    }
                });

        //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 clickBanner(int position) {
        SlideshowEty clickedGameObj = ListUtil.getItem(slideshowEtyLists, position);
        if (clickedGameObj == null) {
            return;
        }
        UMConfigUtils.onEvent(UMConfigUtils.Event.BANNER_CLICK_HORIZONTAL);
        UMConfigUtils.IdEvent.BANNER.commit(clickedGameObj.getId());
        switch (clickedGameObj.getType()) {// 0,类型 1跳转试玩赚钱、2单个任务详情、3信用卡办理、4 H5页面、5 微信二维码任务
            case 1:
                Jump2View.getInstance()
                        .goTryplayView(activity, null);
                break;
            case 2:
                try {
                    Jump2View.getInstance()
                            .goTaskDetailView(activity, EntityUtils.getExtInfo(clickedGameObj.getExt()).getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 3:
                Jump2View.getInstance()
                        .goCreditCardTaskList(activity, 3);
                break;
            case 4:
                if (!TextUtils.isEmpty(clickedGameObj.getObjects())) {
                    Ext ext = EntityUtils.getExtInfo(clickedGameObj.getExt());
                    if (ext.getTitle() == null)//外部浏览器加载H5
                        Jump2View.getInstance().goWeb(activity, ext.getUrl());
                    else//内部WebView加载H5
                        Jump2View.getInstance().goWeb(activity, ext.getUrl(), ext.getTitle());

                }

                break;
            case 5:
                if (!TextUtils.isEmpty(clickedGameObj.getObjects())) {

                    Jump2View.getInstance()
                            .goWeb(
                                    activity,
                                    clickedGameObj.getObjects(),
                                    "微信二维码辅助好友注册任务");
                }

                break;
            case 6://连续任务
                Jump2View.getInstance().goSequentialTaskView(activity);
                break;
            case 9://打卡赚钱
                showToast("打卡赚钱");
                Jump2View.getInstance().goSignCardAct(activity, null);
                break;
            case 7://玩转游戏
                Jump2View.getInstance()
                        .goMainGame(activity);
                break;
            case 11://游戏任务
                Jump2View.getInstance()
                        .goGameMakeMoney(activity, 0);
                break;
            case 12://闲玩任务
                Jump2View.getInstance().goXianwanWeb(activity, null, null);
                break;
            case 13://游戏代充
                Jump2View.getInstance().goGameRecharge(activity, null);
                break;
            case 14://幂动科技
                Jump2View.getInstance().goMiDong(activity, null);
                break;
            case 15://小米游戏列表
                Jump2View.getInstance().goXiaomiGameList(activity, null);
                break;
            default:
                G.showToast(R.string.coming_soon);
                break;
        }
    }

    /**
     * 公共
     */
    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 = SharedPreferences.getInstance().getBoolean("isShowDialog", true);
        if (isShowDialog && !NotificationsUtils.isNotificationEnabled(mContext)) {//没有开启通知权限
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("提示");
            builder.setMessage("是否开启推送?");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences.getInstance().putBoolean("isShowDialog", false);
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    NotificationsUtils.goToNotificationSetting(mContext);
                }
            });
            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);
            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.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        LogUtil.logI("0------" + new Gson().toJson(baseMessage));
                        G.showToast(baseMessage.getMsg());
                    }

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

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

        if (onResumeCount == 0 && CommonUtil.getInstance().addNewTask(activity, userEntity) && homeListEntitysGridview != null)//第一次才调用
        {
            HomeListEntity homeListEntityNewTask = new HomeListEntity();
            homeListEntityNewTask.setTitle("新手任务");
            homeListEntityNewTask.setDesc("新手任务");
            homeListEntityNewTask.setJump("-1");
            homeListEntityNewTask.setIcon(R.mipmap.homepage_xinshourw + "");
            homeListEntitys.add(0, homeListEntityNewTask);
        }
        if (homeListEntitys.size() > 8) {
            HomeListEntity homeListEntity = new HomeListEntity();
            homeListEntity.setTitle("查看更多");
            homeListEntity.setDesc("查看更多");
            homeListEntity.setJump("-2");
            homeListEntity.setIcon(R.mipmap.homepage_chakangd + "");
            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(R.mipmap.homepage_chakangd_click + "");
            } else {
                homeListEntity.setTitle("查看更多");
                homeListEntity.setDesc("查看更多");
                homeListEntity.setIcon(R.mipmap.homepage_chakangd + "");
            }
            homeListEntitysGridview.set(7, homeListEntity);
        }
        adpHomeListGrideview.notifyDataSetChanged();
    }
}
