package com.cooleshow.teacher.ui.income;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineIncomeAdapter;
import com.cooleshow.teacher.adapter.OtherAmountListAdapter;
import com.cooleshow.teacher.bean.AccountDetailBean;
import com.cooleshow.teacher.bean.UserAccountBean;
import com.cooleshow.teacher.contract.FrozenAmountContract;
import com.cooleshow.teacher.databinding.ActivityFrozenAmountLayoutBinding;
import com.cooleshow.teacher.presenter.income.FrozenAmountPresenter;

import java.util.Calendar;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Author by pq, Date on 2022/7/28.
 */
@Route(path = RouterPath.IncomeCenter.TEACHER_FROZEN_AMOUNT)
public class FrozenAmountActivity extends BaseMVPActivity<ActivityFrozenAmountLayoutBinding, FrozenAmountPresenter> implements FrozenAmountContract.FrozenAmountView, View.OnClickListener {

    private OtherAmountListAdapter mIncomeAdapter;
    private int currentPage = 1;
    private String currentFilterDate;
    private Date currentSelectDate;
    private TimePickerView pvTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "冻结明细");
        viewBinding.tvDate.setOnClickListener(this);
        RecyclerView rvAddress = viewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(manager);
        mIncomeAdapter = new OtherAmountListAdapter();
        LayoutInflater inflater = LayoutInflater.from(this);
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        mIncomeAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(mIncomeAdapter);
        mIncomeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        viewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryList(true);
        });
        mIncomeAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryList(false);
                } else {
                    mIncomeAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        reBuildFilter(null);
    }

    private void reBuildFilter(Date date) {
        currentSelectDate = date != null ? date : TimeUtils.getNowDate();
        String targetDateTimeStr = TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"));
        if (TextUtils.equals(targetDateTimeStr, currentFilterDate)) {
            //防止重复条件触发
            return;
        }
        currentFilterDate = targetDateTimeStr;
        currentPage = 1;
        viewBinding.tvDate.setText(currentFilterDate);
        queryList(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null) {
            presenter.getUserAccountDetail();
        }
    }

    private void queryList(boolean isLoading) {
        presenter.userAccountPage(isLoading, currentPage, currentFilterDate);
    }

    @Override
    protected ActivityFrozenAmountLayoutBinding getLayoutView() {
        return ActivityFrozenAmountLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected FrozenAmountPresenter createPresenter() {
        return new FrozenAmountPresenter();
    }

    @Override
    public void userAccountDetailSuccess(AccountDetailBean detailBean) {
        if (!checkActivityExist()) {
            return;
        }
        //冻结金额
        viewBinding.tvAmountValue.setText(detailBean.amountFrozen);
    }

    @Override
    public void userAccountPageSuccess(int page, UserAccountBean data) {
        if (!checkActivityExist()) {
            return;
        }
        if (data != null) {
            if (page == 1) {
                viewBinding.refreshLayout.finishRefresh();
                mIncomeAdapter.getData().clear();
                mIncomeAdapter.notifyDataSetChanged();
                if (data.rows != null && data.rows.size() > 0) {
                    checkHasNext(data.rows.size());
                    mIncomeAdapter.setNewInstance(data.rows);
                }
            } else {
                if (data.rows != null && data.rows.size() > 0) {
                    mIncomeAdapter.getLoadMoreModule().loadMoreComplete();
                    mIncomeAdapter.addData(data.rows);
                    checkHasNext(data.rows.size());
                } else {
                    mIncomeAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        }
    }

    @Override
    public void userAccountPageError(int page) {
        if (!checkActivityExist()) {
            return;
        }
        if (page == 1) {
            viewBinding.refreshLayout.finishRefresh();
        } else {
            if (mIncomeAdapter != null) {
                currentPage--;
                mIncomeAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }


    private boolean hasNext = true;

    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                reBuildFilter(date);
            }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_default_layout, new CustomListener() {
                @Override
                public void customLayout(View v) {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvSubmit = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_finish);
                    TextView ivCancel = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_cancel);
                    tvSubmit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvTime.returnData();
                            pvTime.dismiss();
                        }
                    });
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pvTime.dismiss();
                        }
                    });

                }
            })
                    .setLineSpacingMultiplier(2.5f)
                    .setType(new boolean[]{true, true, false, false, false, false})// 默认全部显示
                    .setTextColorCenter(getResources().getColor(com.cooleshow.base.R.color.color_1a1a1a))//设置选中项的颜色
                    .isDialog(false)//是否显示为对话框样式
                    .setLabel("年", "月", "", "", "", "")
                    .build();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentSelectDate);
        pvTime.setDate(calendar);
        if (!pvTime.isShowing()) {
            pvTime.show();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_date) {
            showTimeSelectPicker();
            return;
        }
    }
}
