package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.graphics.Paint;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.model.entity.AskTop;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;

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

import java.util.List;
import java.util.Locale;

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

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

public class FgtAskGetMoneyRank extends BaseFragment {
    @BindView(R.id.ask_top5_title)
    TextView askTop5Title;
    @BindView(R.id.ask_top5_not_you)
    TextView askTop5NotYou;
    @BindView(R.id.ask_top3_tip)
    ImageView askTop3Tip;
    @BindView(R.id.empty_view_img)
    ImageView emptyViewImg;
    @BindView(R.id.empty_view_msg)
    TextView emptyViewMsg;
    @BindView(R.id.empty_view)
    RelativeLayout emptyView;
    @BindView(R.id.ask_top5_list)
    RecyclerView askTop5List;
    @BindView(R.id.this_last_tv)
    TextView this_last_tv;

    private Activity activity;
    private List<AskTop> list = ListUtil.emptyList();
    private AdbCommonRecycler<AskTop> adapter;

    public static FgtAskGetMoneyRank newInstance(){
        FgtAskGetMoneyRank fgt = new FgtAskGetMoneyRank();
        return fgt;
    }

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

    @Override
    public void onViewCreated() {
        activity = getActivity();

        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        initAskTop5View();
        this_last_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        this_last_tv.getPaint().setAntiAlias(true);//抗锯齿
        initData();
    }
    public void initData() {
//        showProgress();

        initAskTop5(start_time, end_time);
    }

    private void initAskTop5View() {
        list.clear();
        list.add(null);
        askTop5List.setLayoutManager(new LinearLayoutManager(activity));
        //ask_top5_list 解决滑动不流畅问题
        askTop5List.setHasFixedSize(true);
        askTop5List.setNestedScrollingEnabled(false);
        adapter = new AdbCommonRecycler<AskTop>(activity, list) {

            @Override
            public int getItemViewType(int position) {
                return position;
            }

            @Override
            public int getViewIdByType(int type) {
                switch (type) {
                    case 0:
                        return R.layout.x_ask_top5_title;
                    default:
                        return R.layout.x_ask_top5_item;
                }
            }

            @Override
            public void convert(ViewHolder holder, final AskTop item) {
                View itemView = holder.itemView;
                int position = holder.getAdapterPosition();
                if (position == 0) {
                }else {
                    TextView x_ask_top5_item_user = itemView.findViewById(R.id.x_ask_top5_item_user);
                    TextView x_ask_top5_item_money = itemView.findViewById(R.id.x_ask_top5_item_money);
                    TextView x_ask_top5_item_award = itemView.findViewById(R.id.x_ask_top5_item_award);
                    ImageView ask_top5_item_iv = itemView.findViewById(R.id.ask_top5_item_iv);

                    if (item == null) {//空数据占位置
                        itemView.setVisibility(View.INVISIBLE);
                    }else {
                        itemView.setVisibility(View.VISIBLE);
                        ViewUtil.setText(x_ask_top5_item_user, String.format(Locale.CHINA, "昵称\n%s", item.getNickname()));
                        ViewUtil.setText(x_ask_top5_item_money, String.format(Locale.CHINA, "%d", item.getSum_friend()));
                        ViewUtil.setText(x_ask_top5_item_award, item.getPrize());
                        switch (position) {
                            case 1:
                                ask_top5_item_iv.setImageResource(R.mipmap.ask_top_1);
                                break;
                            case 2:
                                ask_top5_item_iv.setImageResource(R.mipmap.ask_top_2);
                                break;
                            case 3:
                                ask_top5_item_iv.setImageResource(R.mipmap.ask_top_3);
                                break;
                            default:
                                ask_top5_item_iv.setVisibility(View.INVISIBLE);
                                break;
                        }
                    }

                }



            }
        };
        askTop5List.setAdapter(adapter);
    }
    private long start_time, end_time;
    private void initAskTop5(long start_time, long end_time) {
        SheepApp.getInstance().getNetComponent().getApiService().getInvitationTop(5,start_time, end_time)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<AskTop> newList = baseMessage.getDataList(AskTop.class);
                        list.clear();
                        list.add(null);
                        boolean hasMe = false;
                        int i = 0;
                        if (!ListUtil.isEmpty(newList)) {

                            list.addAll(newList);
                            String userId = DataUtil.getInstance().getUserId();
                            for (AskTop item : newList) {
                                i++;
                                if (TextUtils.equals(userId, item.getUser_id())) {
                                    hasMe = true;
                                    break;
                                }
                            }
                        }
                        if(askTop5NotYou == null){
                            return;
                        }
                        if(hasMe){
                            askTop5NotYou.setText(String.format(Locale.CHINA ,activity.getString(R.string.congratulation_you_in_rank_top), i+""));
                        }else {
                            askTop5NotYou.setText(getString(R.string.you_not_rank_in_top5));
                        }
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                        if(askTop5NotYou == null){
                            return;
                        }
                        askTop5NotYou.setVisibility(View.VISIBLE);
                    }
                });
    }

    private void notifyDataSetChanged() {
        if(emptyView == null){
            return;
        }
        CommonUtil.getInstance().updateEmptyView(emptyView, list.size() == 1, true);
        adapter.notifyDataSetChanged();
    }

    //显示邀请好友排行榜top5的规则的对话框
    public void showAstTop5Tip() {
        ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("活动说明")
                .setMsg(".每天实时更新排行数据。\n" +
                        ".根据当月已赚赏金（定向货币除外）和邀请人数进行排行\n" +
                        ".每个月前5名可获取排行奖励。\n" +
                        ".每个月月底最后一天24：00可公布结果，获奖的用户需通过“小绵羊领头羊”公众号发送获奖截图证明及收货信息，核对信息真实后，会第一时间发放！\n" +
                        ".本活动最终解释权归成都橙风有量科技有限公司所有！")
                .setMsgGravity(Gravity.START)
                .setTheme(DialogConfig.THEME_PURPLE)
                .setBtnLeftText("我知道了"));
    }


    @OnClick({R.id.ask_top3_tip,R.id.this_last_tv
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ask_top3_tip://提现
                showAstTop5Tip();
                break;
            case R.id.this_last_tv://
                if(this_last_tv.getText().equals(activity.getResources().getString(R.string.last_this_month_rank))){//查上月
                    this_last_tv.setText(activity.getResources().getString(R.string.this_month_rank));
                    askTop5Title.setText(activity.getResources().getString(R.string.last_this_month_rank_top5));
                    long[] longs = CommonUtil.getInstance().getLastMonth();
                    start_time = longs[0] / 1000;
                    end_time = longs[1] / 1000;
                }else {//查本月
                    start_time = 0;
                    end_time = 0;
                    this_last_tv.setText(activity.getResources().getString(R.string.last_this_month_rank));
                    askTop5Title.setText(activity.getResources().getString(R.string.this_month_rank_top5));
                }
                initAskTop5(start_time,end_time);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case ASK_GETMONEY_FRIEND_REFRESH:
                initData();
                break;
        }
    }
}
