package com.kfzs.duanduan.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.ActMain;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.mine.GiftpackListAdapter;
import com.kfzs.duanduan.view.ViewPagerAutoHeigh;
import com.sheep.gamegroup.model.entity.BaseMessage;
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.FastJsonUtils;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.fragment.FgtAskGetMoneyFriend;
import com.sheep.gamegroup.view.fragment.FgtAskGetMoneyRank;
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.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.sunfusheng.marqueeview.MarqueeView;

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.QR_COPY;

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

public class FgtAskgetmoney extends BaseCompatFragment {
    @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_award_info)
    MarqueeView ask_award_info;
    @BindView(R.id.ask_scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.indicator)
    TabLayout indicator;
    @BindView(R.id.pager)
    ViewPagerAutoHeigh pager;
    @BindView(R.id.my_invitation_tv)
    TextView my_invitation_tv;
    @BindView(R.id.copy_my_invitation_tv)
    TextView copy_my_invitation_tv;

    private FriendAndAwardEntity mEntity;
    Unbinder unbinder;
    private Activity activity;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.x_ask_getmoney_act_layout);
        activity = getActivity();
        if(activity instanceof ActMain){
            TitleBarUtils.getInstance()
                    .setTitle(mContentView, "邀请赚钱")
                    .setTitleListen(mContentView,0,null);
        }else {
            TitleBarUtils.getInstance()
                    .setTitle(mContentView, "邀请赚钱")
                    .setTitleFinish(mContentView, activity);
        }
        unbinder = ButterKnife.bind(this, mContentView);

//
//        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.png");
//                16,18,19
        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) ask_top_1.getLayoutParams();
        layoutParams1.height = G.WIDTH * 660 / 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);

        showViewpage();

        initData();

        initListener();

    }

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

    @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 (ask_award_info != null) {
                            //开始滚动
                            ask_award_info.stopFlipping();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    default:
                        if (ask_award_info != null) {
                            //开始滚动
                            ask_award_info.startFlipping();
                        }
                        break;
                }
                return false;
            }
        });
    }

    private UserEntity userEntity;

    public void initData() {
        ViewUtil.newInstance().showProgress(activity);
        SheepApp.getInstance().getNetComponent().getApiService().FriendCountAndAward()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress(activity);
                        if(BuildConfig.DEBUG)
                            G.showToast(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if(baseMessage!=null){
                            mEntity = FastJsonUtils.toBean( JSONObject.toJSONString(baseMessage.getData()),FriendAndAwardEntity.class);
                            ViewUtil.newInstance().hideProgress(activity);
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvSize.setText(mEntity.getFriend_count() + "");
                                    tvMoney.setText(mEntity.getAward());
                                }
                            });
                        }else{
                            onError(baseMessage);
                        }

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



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

        if (ask_award_info != null) {
            //停止滚动
            ask_award_info.stopFlipping();
        }
    }

    //显示分享对话框
    public void showShareView() {
        String url = userEntity.getShareLink();
        String description = mEntity.getShare_desc();
        ViewUtil.showShareDialog(activity, url, description);
    }

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

    private void showViewpage() {
        mAdapter = new GiftpackListAdapter(getChildFragmentManager(), activity.getApplicationContext());
        mAdapter.add(new FgtAskGetMoneyRank(), tabNames[0]);
        mAdapter.add(new FgtAskGetMoneyFriend(), 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})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.copy_my_invitation_tv:
                if(TextUtils.isEmpty(my_invitation_tv.getText().toString()))
                    return;
                QR_COPY.onEvent();
                StringUtils.CopyText(userEntity.getInvitation_code()+"");
                G.showToast("复制邀请码成功");
                break;
            case R.id.ask_invite_tv:
                showShareView();
                break;
        }
    }
}
