package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
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.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventTypes;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.FriendAndAwardEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
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.StringUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.activity.AskGetMoneyAct;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;

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

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

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

/**
 * Created by ljy on 2018/8/20.
 */

public class FgtAskGetMoney extends BaseFragment {
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.tv_size)
    TextView tvSize;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.ask_bg)
    ImageView ask_bg;
    @BindView(R.id.ask_top_1)
    View ask_top_1;
    @BindView(R.id.ask_top_2)
    View ask_top_2;
    @BindView(R.id.ask_top_3)
    View ask_top_3;
    @BindView(R.id.ask_scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.indicator)
    TabLayout indicator;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.my_invitation_tv)
    TextView my_invitation_tv;
    @BindView(R.id.ask_act_code)
    TextView ask_act_code;
    @BindView(R.id.copy_my_invitation_tv)
    TextView copy_my_invitation_tv;

    private FriendAndAwardEntity mEntity;

    private Activity activity;

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

    //在viewPager的第一个位置或者在activity中通过transaction.replace(R.id.frame_container, fragment);方式加载的话，需要设置为true
    private boolean isFirstFgt;
    @Override
    public void onViewCreated() {
        activity = getActivity();
        isFirstFgt = activity instanceof AskGetMoneyAct;
//
//        String content = "<!DOCTYPEhtml>\n" +
//                "<html>\n" +
//                "  <head>\n" +
//                "    <title>HTML字符串</title>\n" +
//                "    <metahttp-equivmetahttp-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n" +
//                "    <meta name=\"viewport\" content=\"width=" + G.WIDTH + ", user-scalable=no\">\n" +
//                "    <style type=\"text/css\">\n" +
//                "      body {\n" +
//                "        margin: 0;\n" +
//                "        padding: 0;\n" +
//                "      }\n" +
//                "      img {\n" +
//                "        padding: 0;\n" +
//                "        margin: 0;\n" +
//                "      }\n" +
//                "    </style>\n" +
//                "  </head>\n" +
//                "  <body>\n" +
//                "    <img src=\"http://cdngame.kuaifazs.com/yaoqingzq_bg.png\" width=\"100%\">\n" +
//                "  </body>\n" +
//                "</html>";
//        ask_bg.getSettings().setDefaultTextEncodingName("UTF-8");
//        ask_bg.loadData(content, "text/html", "UTF-8");
        GlideImageLoader.setImage(ask_bg, "http://cdngame.kuaifazs.com/yaoqingzq_bg_3.png");
//                16,18,19
        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) ask_top_1.getLayoutParams();
        layoutParams1.height = G.WIDTH * 600 / 625;
        ask_top_1.setLayoutParams(layoutParams1);
        LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) ask_top_2.getLayoutParams();
        layoutParams2.height = G.WIDTH * 112 / 625;
        ask_top_2.setLayoutParams(layoutParams2);
        RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) ask_top_3.getLayoutParams();
        layoutParams3.topMargin = G.WIDTH * 1442 / 1080;
        ask_top_3.setLayoutParams(layoutParams3);
        ViewUtil.setDefaultText(tvSize);
        ViewUtil.setDefaultText(tvMoney);
        ViewUtil.setDefaultText(my_invitation_tv);
        ViewUtil.setDefaultText(ask_act_code);

        initListener();
        if(isFirstFgt){
            showViewPager();
            try {
                initData(true);
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
    }

    @Override
    protected void initViewOnVisibleToUser() {
        if(!isFirstFgt) {
            showViewPager();
        }
    }

    @Override
    public void initDataOnVisibleToUser() {
        if(!isFirstFgt) {
            try {
                initData(true);
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        }
    }

    public void initListener() {

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

    public void refreshData() {
        initData(false);
    }

    private UserEntity userEntity;

    public void initData(final boolean isNotRefresh) {
        if (!isNotRefresh) {
            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.ASK_GETMONEY_FRIEND_REFRESH));
        }
        SheepApp.getInstance().getNetComponent().getApiService().FriendCountAndAward()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (BuildConfig.DEBUG)
                            G.showToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage != null) {
                            boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.FRIEND_COUNT_AND_AWARD);
                            if (mEntity == null || isNewData) {
                                mEntity = baseMessage.getData(FriendAndAwardEntity.class);
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mEntity != null) {
                                            ViewUtil.setText(tvSize, String.valueOf(mEntity.getFriend_count()));
                                            ViewUtil.setText(tvMoney, String.valueOf(mEntity.getAward()));
                                        }
                                    }
                                });
                            }
                        }

                    }
                });
        CommonUtil.getInstance().updateUserInfo(new Action1<UserEntity>() {
            @Override
            public void call(UserEntity result) {
                if (result != null) {
                    boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.get_info);
                    if (userEntity == null || isNewData) {
                        userEntity = result;
                        String audit_total_audit = String.format(activity.getResources().getString(R.string.my_invitation_str), userEntity.getInvitation_code());
                        ask_act_code.setText(audit_total_audit);
                        my_invitation_tv.setText(audit_total_audit);
                    }
                }
            }
        });
    }

    public static final String[] tabNames = {"排行榜", "好友列表"};
    private TitleFragmentListAdapter mAdapter;

    private void showViewPager() {
        mAdapter = new TitleFragmentListAdapter(getChildFragmentManager());
        mAdapter.add(FgtAskGetMoneyRank.newInstance(), tabNames[0]);
        mAdapter.add(FgtAskGetMoneyFriend.newInstance(), tabNames[1]);
        pager.setOffscreenPageLimit(2);
        pager.setAdapter(mAdapter);
        indicator.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(pager));

        indicator.setupWithViewPager(pager);
        CommonUtil.getInstance().reflex(indicator, activity);
    }

    @OnClick({R.id.copy_my_invitation_tv, R.id.ask_invite_tv, R.id.refresh, R.id.ask_act_rule, R.id.ask_act_code_copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.copy_my_invitation_tv:
            case R.id.ask_act_code_copy:
                if (userEntity == null) {
                    G.showToast(R.string.loading_data);
                    return;
                }
                QR_COPY.onEvent();
                StringUtils.CopyText(userEntity.getInvitation_code() + "");
                G.showToast(R.string.success_copy_inv_code);
                break;
            case R.id.ask_act_rule:
                ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("活动规则").setBtnLeftText("我知道了").setTheme(DialogConfig.THEME_PURPLE)
                        .setMsg("首邀好友，好友下载并登录小绵羊，既可获得2.5绵羊币\n首邀好友完成新手任务，邀请人可额外再获得2.5绵羊币"));
                break;
            case R.id.refresh://只是一个点击，用来遮盖底部不可见的view的点击
                break;
            case R.id.ask_invite_tv:
                Jump2View.getInstance().goActInvitation(activity);
                break;
        }
    }
}
