package com.yidianling.user.mine;

import android.annotation.SuppressLint;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.base.config.HttpConfig;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.TitleBar;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.user.R;
import com.yidianling.user.UserConstants;
import com.yidianling.user.UserHelper;
import com.yidianling.user.api.utils.UserApiServiceUtils;
import com.yidianling.user.bean.FundData;
import com.yidianling.user.mine.data.AppDataManager;
import com.yidianling.user.mine.view.LoadMoreFooterView;

import org.jetbrains.annotations.NotNull;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 资金明细
 * Created by softrice on 15/12/1.
 */
@Route(path = "/mine/AccountHistoryActivity")
public class AccountHistoryActivity extends BaseActivity implements PtrHandler, LoadMoreHandler {

    AccountHistoryListAdapter adapter;
    FundData fundData;


    int page = 0;
    boolean hasMore = true;

    private String available = "0.00";

    LoadMoreFooterView loadMoreFooterView;
    //    @BindView(R.id.title_bar)
    TitleBar title_bar;
    //    @BindView(R.id.lv_content)
    ListView lv_content;
    //    @BindView(R.id.ll_empty)
    LinearLayout ll_empty;
    //    @BindView(R.id.load_more_list_view_container)
    LoadMoreListViewContainer load_more_list_view_container;
    //    @BindView(R.id.store_house_ptr_frame)
    PtrFrameLayout store_house_ptr_frame;

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }

    @Override
    protected int layoutResId() {
        return R.layout.user_mine_activity_account_history;
    }

    @Override
    protected void initDataAndEvent() {
        title_bar = findViewById(R.id.title_bar);
        lv_content = findViewById(R.id.lv_content);
        ll_empty = findViewById(R.id.ll_empty);
        load_more_list_view_container = findViewById(R.id.load_more_list_view_container);
        store_house_ptr_frame = findViewById(R.id.store_house_ptr_frame);
        init();
    }


    void init() {
        title_bar.setmRightText("提现");
        title_bar.setOnRightTextClick(new TitleBar.OnTitleBarTextClick() {
            @Override
            public void onClick(View view, boolean isActive) {
                //未绑定手机号弹窗提示去绑定
                if (!UserHelper.INSTANCE.isBindPhone()) {
                    CommonDialog.create(AccountHistoryActivity.this)
                            .setLeftOnclick("忍痛放弃", null)
                            .setRightClick("果断绑定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(UserApiServiceUtils.INSTANCE.provideUserApiService().inputPhoneIntent(AccountHistoryActivity.this, UserConstants.BIND_PHONE_ACTION));
                                }
                            })
                            .setMessage("\n为了您的账户安全，请先绑定手机\n")
                            .show();
                    return;
                }

//                String money = null;
//                if (adapter.getCount() > 1) {
//                    money = ((FundData.Fund) adapter.getItem(0)).available;
//                } else {
//                    money = "0.00";
//                }
                WithDrawActivity.Companion.start(AccountHistoryActivity.this, available);
            }
        });
        // header
        final MaterialHeader header = new MaterialHeader(this);
        int[] colors = getResources().getIntArray(R.array.user_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        final int padding = (int) getResources().getDimension(R.dimen.platform_default_dis_size);
        header.setPadding(0, padding, 0, padding);
        header.setPtrFrameLayout(store_house_ptr_frame);
        store_house_ptr_frame.setHeaderView(header);
        store_house_ptr_frame.setPtrHandler(this);
        store_house_ptr_frame.addPtrUIHandler(header);
        // 使用默认样式
        //load_more_list_view_container.useDefaultHeader();
        loadMoreFooterView = new LoadMoreFooterView(this);
        load_more_list_view_container.setLoadMoreUIHandler(loadMoreFooterView);
        load_more_list_view_container.setLoadMoreView(loadMoreFooterView);
        load_more_list_view_container.setLoadMoreHandler(this);
        adapter = new AccountHistoryListAdapter(this);

//        getData(false);
        lv_content.setEmptyView(ll_empty);
        lv_content.setAdapter(adapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    return;
                }
                FundData.Fund fund = adapter.getDataList().get(position - 1);
                if ("1".equals(fund.type_int)) {//倾诉

                    H5Params h5Params = new H5Params(fund.url + "orderid=" + fund.orderid, null);
                    h5Params.setShowMenu(true);
                    NewH5Activity.start(AccountHistoryActivity.this, h5Params);
                } else if ("2".equals(fund.type_int)) {//订单详情
                    H5Params h5Params = new H5Params(HttpConfig.Companion.getH5_URL() + "booking/order-detail?orderid=" + fund.orderid, null);
                    NewH5Activity.start(AccountHistoryActivity.this, h5Params);
                }
            }
        });
    }

    @SuppressLint("CheckResult")
    void getData(final boolean loadMore) {
        if (loadMore && !hasMore) {
            load_more_list_view_container.loadMoreFinish(false, false);
            return;
        }
        if (loadMore) {
            page++;
        } else {
            page = 1;
        }
        showProgressDialog();
        AppDataManager.INSTANCE.getHttp().getMyFundList(new FundListParam(1, page + ""))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fundData -> {
                    dismissProgressDialog();
                    load_more_list_view_container.loadMoreFinish(false, false);
                    if (fundData == null || fundData.fund.size() < UserConstants.FUND_PAGE_SIZE) {
                        hasMore = false;
                    }
                    load_more_list_view_container.loadMoreFinish(false, hasMore);
                    if (!loadMore)
                        adapter.setDataList(fundData.fund);
                    else if (fundData.fund != null)
                        adapter.addDataList(fundData.fund);
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        dismissProgressDialog();
                        ToastHelper.Companion.show(msg);
                    }
                });


    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, lv_content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                store_house_ptr_frame.refreshComplete();
            }
        }, 1800);
        getData(false);
        getMyBalance();
    }


    @SuppressLint("CheckResult")
    private void getMyBalance() {
        AppDataManager.INSTANCE.getHttp().getMyBalance()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(balanceBeanBaseResponse -> {
                    if (balanceBeanBaseResponse.code == 200) {
                        if (balanceBeanBaseResponse.data != null) {
                            available = balanceBeanBaseResponse.data.availableMoney;
                            if (adapter != null) {
                                adapter.setAvailable(balanceBeanBaseResponse.data.availableMoney);
                            }
                        }
                    } else {
                        ToastUtil.toastShort(balanceBeanBaseResponse.msg);
                    }
                }, throwable -> {

                });
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        getData(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData(false);
        getMyBalance();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
