package com.kfzs.duanduan.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.react.ReactUtil;
import com.kfzs.duanduan.react.SharedPreferences;
import com.sheep.gamegroup.absBase.BaseActivity;
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.ImageHeadChange;
import com.sheep.gamegroup.event.MoneyChange;
import com.sheep.gamegroup.event.UserNameChange;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.BulletinEnty;
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.NewbieTask;
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.entity.WebviewEntity;
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.AppUtil;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ImageGlarryDrawable;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.PreferenceUtils;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
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.TryMakeMoneyAdp;
import com.sheep.gamegroup.view.customview.SheepViewPager;
import com.sheep.gamegroup.view.dialog.DialogNewbieTaskList;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sunfusheng.marqueeview.MarqueeView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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.schedulers.Schedulers;

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.homepage_item_banner_layout)
    RelativeLayout homepage_item_banner_layout;
    @BindView(R.id.icon_layout)
    RelativeLayout icon_layout;

    @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.user_layout)
    LinearLayout userLayout;
    @BindView(R.id.withdrawal)
    TextView withdrawal;
    @BindView(R.id.my_price)
    TextView myPrice;
    @BindView(R.id.my_all_price)
    TextView myAllPrice;
    @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.viewpager_banner)
    SheepViewPager viewpager_banner;
    @BindView(R.id.group_banner)
    RadioGroup group_banner;
    @BindView(R.id.scrollView)
    ScrollView 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;

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

    //recyclerview
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private int position = 0;
    private List<TaskReleaseEty> releaseEtyLists = new ArrayList<>();
    private List<SlideshowEty> slideshowEtyLists = 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;

    Handler mHanderl = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    refalsh();
                    break;
                case 1:
                    tryMakeMoneyAdp.setIs_succession(3);
                    if(releaseEtyLists != null && releaseEtyLists.size()>0){

                        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RELEASE_TASK, releaseEtyLists), position>2?1:position);
                    }
                    tryMakeMoneyAdp.notifyDataSetChanged();
                    if(recyclerview == null)
                        recyclerview = mContentView.findViewById(R.id.recyclerview);
                    recyclerview.setFocusable(false);
                    scrollView.scrollTo(0,0);
                    break;
            }

        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.homepage_act_layout);
        showPDialog();
        initView();
        initListener();
        TestUtil.testChange(getActivity(), (TextView) getViewById(R.id.test_change));
    }

    public void initView() {
        EventBus.getDefault().register(this);
        activity = getActivity();
        ButterKnife.bind(this, mContentView);
        DaggerSmallSheepComponent.builder()
                .netComponent(SheepApp.get(getContext()).getNetComponent())
                .smallSheepModule(new SmallSheepModule(this))
                .tryMakeMoneyModule(new TryMakeMoneyModule(this))
                .build()
                .inject(this);
        recyclerInitView();

    }


    private void refalsh() {

        if (myPrice == null || userEntity == null) {
            return;
        }
        myPrice.setText(userEntity.getBalance() + " 元");
        myAllPrice.setText("累计资产 " + userEntity.getTotal_asset() + " 元");
        nameTv.setText(userEntity.getNickname() + "");//绵羊号：123456789
        sheepNumTv.setText("绵羊号：" + userEntity.getInvitation_code());
        if (ReactUtil.isSmallDebug()) {
            sheepNumTv.append("\n\n邀请人：");
            sheepNumTv.append(userEntity.getParent_code());
        }

        Glide.with(activity)
                .load(userEntity.getAvatar())
                .apply(new RequestOptions().circleCrop().placeholder(R.drawable.icon))
                .into(iconImgIv);

    }


    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:
                        if (upview1 != null) {
                            //开始滚动
                            upview1.startFlipping();
                        }
                        if (homepageItemNoticeMv != null) {
                            //开始滚动
                            homepageItemNoticeMv.startFlipping();
                        }
                        break;
                    default:
                        if (upview1 != null) {
                            //开始滚动
                            upview1.startFlipping();
                        }
                        if (homepageItemNoticeMv != null) {
                            //开始滚动
                            homepageItemNoticeMv.startFlipping();
                        }
                        break;
                }
                return false;
            }
        });

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
                refresh.setRefreshing(false);
            }
        });

        //recyclerView 禁止滑动
//        recyclerview.setNestedScrollingEnabled(false);
    }

    public void initData() {

        if (upview1 != null) {
            //停止滚动
            upview1.stopFlipping();
            upview1.startFlipping();
        }
        if (homepageItemNoticeMv != null) {
            //停止滚动
            homepageItemNoticeMv.stopFlipping();
            homepageItemNoticeMv.startFlipping();
        }
        pagePresenter.getUserInfo();

        if (views.size() < 1) {
            pagePresenter.getAwardDetail();
        }

        initWechatIsOpen();
        recyclerInitData();//任务
        pagePresenter.bulletin(null);//轮播
        pagePresenter.slideshow(null);//公告
        pagePresenter.homeList();//首页list

    }

    /**
     * recyclerview
     */
    private void recyclerInitView() {

        recyclerview.setLayoutManager(new LinearLayoutManager(activity));
        tryMakeMoneyAdp = new TryMakeMoneyAdp(getActivity());
        for (int i = 0; i < 2; i++) {
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
        }
        recyclerview.setAdapter(tryMakeMoneyAdp);

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

    private void recyclerInitData() {


        position = 0;
        releaseEtyLists.clear();
        tryMakeMoneyAdp.clear();
        tryMakeMoneyAdp.addType(1);
        for (int i = 0; i < 2; i++) {
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
        }
        tryMakeMoneyAdp.setTaskAcceptedEty(null);

        RequestParameEty parameEty = new RequestParameEty();
        parameEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(1,
                                100,
                                1,
                                1,
                                0,
                                0,
                                -1,
                                0));

        tryMakeMoneyPresenter.releaseTask(parameEty);
    }

    /**
     * 获取微信挂机是否开启状态
     */
    private void initWechatIsOpen() {
    }

    @OnClick({R.id.recharge, R.id.user_layout, R.id.withdrawal, R.id.try_play_layout,
            R.id.invitation_layout, R.id.lying_layout, R.id.newbie_task,
            R.id.card_layout, R.id.icon_layout, R.id.info_layout, R.id.homepage_wxfz,
            R.id.q_iv, R.id.q_name_tv, R.id.q_dec_tv,
            R.id.lying_iv, R.id.lying_dec_tv, R.id.lying_name_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_layout:
                break;
            case R.id.withdrawal:
                Jump2View.getInstance().goWithdrawal(activity, null);
                break;
            case R.id.try_play_layout://试玩赚钱
                Jump2View.getInstance().goTryplayView(activity, null);
                break;
            case R.id.invitation_layout://邀请赚钱
                Jump2View.getInstance().goAskGetMoney(activity, null);
                break;
            case R.id.card_layout://办卡赚钱
                Jump2View.getInstance().goCreditCardTaskList(activity, null);
                break;
            case R.id.lying_layout://跳转到游戏页面
                Jump2View.getInstance()
                        .goMainGame(activity);

                break;
            case R.id.newbie_task://新手任务
                if(getActivity() instanceof BaseActivity){
                    ((BaseActivity) getActivity()).showProgress();
                }
                UMConfigUtils.onEvent(UMConfigUtils.Event.SHEEP_NEWBIE_TASK_LIST);
                SheepApp.getInstance().getNetComponent().getApiService().getNewbieTask()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(getContext()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                if(getActivity() instanceof BaseActivity){
                                    ((BaseActivity) getActivity()).hideProgress();
                                }
                                List<NewbieTask> newbieTaskList = baseMessage.getDatas(NewbieTask.class);
                                DialogNewbieTaskList.showDialog(getActivity(), newbieTaskList);
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                if(getActivity() instanceof BaseActivity){
                                    ((BaseActivity) getActivity()).hideProgress();
                                }
                                G.showToast(!TextUtils.isEmpty(baseMessage.getMsg()) ? baseMessage.getMsg() : "网络错误，请重启重试");
                            }
                        });
                break;
            case R.id.homepage_wxfz://微信辅助任务
                Jump2View.getInstance().tryGoWxfz(activity,null);
                break;
            case R.id.icon_layout://
                if(BuildConfig.DEBUG) {
                    TestUtil.test(activity);
                }else
                    Jump2View.getInstance().goPersonnalCenterView(activity, null);
                break;
            case R.id.info_layout://其它信息
                Jump2View.getInstance().goPersonnalCenterView(activity, null);
                break;
            case R.id.q_iv://Q币充值
            case R.id.q_name_tv:
            case R.id.recharge:
            case R.id.q_dec_tv:
//                G.showToast("Q币充值");
                Jump2View.getInstance().goRechargeQAct(activity,null);
                break;
            case R.id.lying_iv://躺着赚钱
            case R.id.lying_dec_tv:
            case R.id.lying_name_tv:
                Jump2View.getInstance().tryGoLyingView(activity, null);
                break;
        }
    }

    @Override
    public void updateData2View(Object o) {
        if (o == null) {
            return;
        }
        BaseMessage baseMessage = (BaseMessage) o;
        userEntity = JSON.parseObject(JSONObject.toJSONString(baseMessage.getData()), UserEntity.class);
        //保存用户id信息
        PreferenceUtils.setPrefString(SheepApp.mContext, UMConfigUtils.LOGIN_OPENID, userEntity.getOpen_id());
        //统计用户登录信息
        UMConfigUtils.onProfileSignIn();
        try {
            MyDbManager.getInstance().saveOrUpdateUser(userEntity);

//            userEntity = MyDbManager.getInstance().dbFindUser();
            Log.e("------userEntity", userEntity.getNickname() + "|" + userEntity.getMobile() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHanderl.sendEmptyMessage(0);
        //PersionInfoAct.java与AskGetMoneyAct.java中分享二维码时的图片预下载
        Glide.with(this)
                .load(AppUtil.getQRLink(userEntity.getShare_link(), 800))
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                .preload(800, 800);
        Jump2View.getInstance().tryShowAgreementOrNewbieTask(activity, userEntity, newbie_task);
    }

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

    }

    @Override
    public void acceptedTaskUpdataView(Object o) {

    }

    @Override
    public void failAcceptedTask2View(Object o) {

    }

    @Override
    public void giveUpTaskSuccesView(Object o) {
        G.showToast("取消任务成功");
        recyclerInitData();

    }

    @Override
    public void giveUpTaskFailView(Object o) {

    }

    @Override
    public void returnTaskTaskUpdataView(Object o) {


        try {
            position = 0;
            BaseMessage baseMessage = (BaseMessage) o;
            List<TaskAcceptedEty> taskAcceptedEty = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), TaskAcceptedEty.class);
            if(taskAcceptedEty != null && taskAcceptedEty.size()>0){
                tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, taskAcceptedEty), position);
                tryMakeMoneyAdp.addPresenter(tryMakeMoneyPresenter);
                position++;
            }

//            mhandler.sendEmptyMessage(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHanderl.sendEmptyMessage(1);
    }

    @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(" 网络错误！");
        }
        mHanderl.sendEmptyMessage(1);
    }

    @Override
    public void releaseTaskTaskUpdataView(Object o) {

        position = 0;
        try {
            BaseMessage baseMessage = (BaseMessage) o;
            List<TaskReleaseEty> releaseEtyList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), TaskReleaseEty.class);
            if (releaseEtyList != null) {
                releaseEtyLists.addAll(releaseEtyList);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //请求正在运行中的任务
        CommonUtil.getInstance()
                .getRunTask(tryMakeMoneyPresenter,
                        3);
    }

    @Override
    public void failReleaseTask2View(Object o) {
        CommonUtil.getInstance()
                .getRunTask(tryMakeMoneyPresenter,
                        3);
    }

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


    }

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

    }

    @Override
    public void successSlideshow(BaseMessage baseMessage) {

        try {
            List<SlideshowEty> slideshowEtyList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), SlideshowEty.class);
            if (slideshowEtyList != null && slideshowEtyList.size()>0) {
                slideshowEtyLists.clear();
                for(SlideshowEty slideshowEty:slideshowEtyList){
                    slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
                    slideshowEtyLists.add(slideshowEty);
                }

                bindBanner();
            }else {
                homepage_item_banner_layout.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failbulletin(BaseMessage baseMessage) {

    }

    @Override
    public void successbulletin(BaseMessage baseMessage) {

        try {
            List<BulletinEnty> bulletinEntyList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), BulletinEnty.class);
            if (bulletinEntyList != null && bulletinEntyList.size() >0) {
                bulletinEntyLists.clear();
                bulletinEntyLists.addAll(bulletinEntyList);
                inviteNotice(bulletinEntyLists);
            }else {
                homepageItemNoticeLayout.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void successhomeList(BaseMessage baseMessage) {
        try{
            List<HomeListEntity> homeListEntity = JSONArray.parseArray(
                    JSONArray.toJSONString(baseMessage.getData()),
                    HomeListEntity.class
            );
            if(homeListEntity != null && homeListEntity.size()> 0){
                home_list_gridview_layout.setVisibility(View.VISIBLE);
                homeListEntitys.clear();
                homeListEntitysGridview.clear();
                homeListEntitysListview.clear();
                homeListEntitys.addAll(homeListEntity);
                boolean isShowQB = false;
                for (int i=0;i<homeListEntitys.size();i++){
                    if(i<4){
                        homeListEntitysGridview.add(homeListEntitys.get(i));
                    }else {
                        homeListEntitysListview.add(homeListEntitys.get(i));
                    }
                    if(homeListEntitys.get(i).getJump().equals("6")){//6Q币充值
                        isShowQB = !isShowQB;
                    }
                }
                SheepApp.getInstance().setShowQB(isShowQB);
                adpHomeListGrideview.notifyDataSetChanged();
                adpHomeListListview.notifyDataSetChanged();
                home_list_gridview_listview.setVisibility(homeListEntitysListview.isEmpty() ? View.GONE : View.VISIBLE);
            }else {
                home_list_gridview_layout.setVisibility(View.GONE);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void failhomeList(BaseMessage baseMessage) {
        home_list_gridview_layout.setVisibility(View.GONE);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (pagePresenter != null) {
            initData();
        }

    }

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

    private void setViews(final List<MoreDataEntity> loginEty) {

        invite(loginEty);
//        new Handler().postDelayed(new Runnable(){
//            public void run() {
//
//            }
//        },60000*2);


    }

    private void invite(final List<MoreDataEntity> loginEty) {
        views.clear();
        upview1.removeAllViews();
        for (MoreDataEntity entity : loginEty) {
            StringBuilder sb = new StringBuilder();
            sb.append(TimeStamp2Date(entity.getTime())).append("   ");
            sb.append(entity.getName()).append("   ");
            sb.append(entity.getDesc());
//            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.x_item_view, null);
//            TextView tv_desc = moreView.findViewById(R.id.tv_desc);
//            tv_desc.setText(sb.toString());
            TextView moreView = (TextView) LayoutInflater.from(getActivity()).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:
                initData();
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UserNameChange done) {
        UserEntity enity = userEntity;
        enity.setNickname(done.getNikeName());
        userEntity = enity;
        refalsh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MoneyChange done) {
        UserEntity enity = userEntity;
        enity.setBalance(done.getBalance());
        enity.setTotal_asset(done.getTotal_asset());
        userEntity = enity;
        refalsh();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ImageHeadChange done) {
        UserEntity enity = userEntity;
        enity.setAvatar(done.getAvatar());
        userEntity = enity;
        refalsh();
    }


    @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);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

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

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            userEntity = MyDbManager.getInstance().dbFindUser();
            if (userEntity != null) {
                refalsh();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    private ImageGlarryDrawable mImageGlarryStr;
    private void bindBanner() {
        homepage_item_banner_layout.setVisibility(View.VISIBLE);
        if (mImageGlarryStr != null) {
            mImageGlarryStr.init((ArrayList<SlideshowEty>) slideshowEtyLists, ImageView.ScaleType.CENTER_CROP);
            mImageGlarryStr.notifyAll();
            return;
        }
        mImageGlarryStr = new ImageGlarryDrawable((Activity) mContext, viewpager_banner, group_banner);
        mImageGlarryStr.init((ArrayList<SlideshowEty>) slideshowEtyLists, ImageView.ScaleType.CENTER_CROP);
        mImageGlarryStr.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SlideshowEty clickedGameObj = slideshowEtyLists.get(position);

                UMConfigUtils.onEvent(UMConfigUtils.Event.BANNER_CLICK_HORIZONTAL);
                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()
                                .goTryplayView(activity, 1);
                        break;
                }
            }
        });
    }

    /**
     * 公共
     */
    private void inviteNotice(final  List<BulletinEnty> bulletinEntyList) {
        homepageItemNoticeLayout.setVisibility(View.VISIBLE);
//        List<String> infoList = new ArrayList<>();
//        for(BulletinEnty bulletinEnty: bulletinEntyList){
//            infoList.add(bulletinEnty.getContent()+"");
//        }
//        homepageItemNoticeMv.startWithList(infoList, R.anim.anim_left_in,R.anim.anim_right_out);

        for (BulletinEnty entity : bulletinEntyList) {
            StringBuilder sb = new StringBuilder();
            sb.append(entity.getContent()).append("   ");
            TextView moreView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.x_item_view, null);
            moreView.setText(sb.toString());
            homepageItemNoticeMv.addView(moreView);
        }
        if (!homepageItemNoticeMv.isAutoStart()) {
            homepageItemNoticeMv.stopFlipping();
            homepageItemNoticeMv.startFlipping();
        }


    }

    /**
     * 提示用户开启推送通知权限
     * 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();
        }

    }
}
