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.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
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.IncomeFilterBean;
import com.cooleshow.teacher.bean.UserAccountBean;
import com.cooleshow.teacher.contract.FrozenAmountContract;
import com.cooleshow.teacher.databinding.ActivityFrozenAmountLayoutBinding;
import com.cooleshow.teacher.databinding.ActivityPendingAmountLayoutBinding;
import com.cooleshow.teacher.presenter.income.FrozenAmountPresenter;
import com.cooleshow.teacher.presenter.income.PendingAmountPresenter;

import java.util.ArrayList;
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_PENDING_AMOUNT)
public class PendingAmountActivity extends BaseMVPActivity<ActivityPendingAmountLayoutBinding, PendingAmountPresenter> implements FrozenAmountContract.FrozenAmountView, View.OnClickListener {

    private MineIncomeAdapter mIncomeAdapter;
    private String currentIncomeFilterStatus = "";
    private int currentPage = 1;
    private String currentFilterDate;
    private Date currentSelectDate;
    private TimePickerView pvTime;
    private ArrayList<IncomeFilterBean> mFilterStatusBeans;
    private OptionsPickerView mIncomeTypeSelector;

    @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);
        viewBinding.tvIncomeType.setOnClickListener(this);
        RecyclerView rvAddress = viewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(manager);
        mIncomeAdapter = new MineIncomeAdapter();
        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();
                }
            }
        });
        buildDefaultStatusFilterList();
        reBuildFilter(null, "");
    }

    private void buildDefaultStatusFilterList() {
        mFilterStatusBeans = new ArrayList<>();
        mFilterStatusBeans.add(new IncomeFilterBean("", "全部类型"));
        mFilterStatusBeans.add(new IncomeFilterBean("PRACTICE", "陪练课"));
        mFilterStatusBeans.add(new IncomeFilterBean("LIVE", "直播课"));
        mFilterStatusBeans.add(new IncomeFilterBean("VIDEO", "视频课"));
        mFilterStatusBeans.add(new IncomeFilterBean("MUSIC", "乐谱"));
        mFilterStatusBeans.add(new IncomeFilterBean("LIVE_SHARE", "直播课推荐"));
        mFilterStatusBeans.add(new IncomeFilterBean("VIDEO_SHARE", "视频课推荐"));
        mFilterStatusBeans.add(new IncomeFilterBean("MUSIC_SHARE", "乐谱推荐"));
        mFilterStatusBeans.add(new IncomeFilterBean("VIP_SHARE", "小酷Ai推荐"));
        mFilterStatusBeans.add(new IncomeFilterBean("MALL_SHARE", "商品推荐"));
        mFilterStatusBeans.add(new IncomeFilterBean("ACTI_REGIST_SHARE", "活动推广"));
        mFilterStatusBeans.add(new IncomeFilterBean("ALBUM_SHARE", "专辑分润"));
    }


    private void reBuildFilter(Date date, String status) {
        currentSelectDate = date != null ? date : TimeUtils.getNowDate();
        String targetDateTimeStr = TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"));
        if (TextUtils.equals(targetDateTimeStr, currentFilterDate) && TextUtils.equals(currentIncomeFilterStatus, status)) {
            //防止重复条件触发
            return;
        }
        currentFilterDate = targetDateTimeStr;
        currentIncomeFilterStatus = !TextUtils.isEmpty(status) ? status : "";
        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, currentIncomeFilterStatus, currentFilterDate);
    }

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

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

    @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();
            }
        }
    }

    @Override
    public void userAccountDetailSuccess(AccountDetailBean detailBean) {
        if (!checkActivityExist()) {
            return;
        }
        //待入账金额
        viewBinding.tvAmountValue.setText(detailBean.amountUnrecorded);
    }


    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, currentIncomeFilterStatus);
            }).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();
        }
    }

    private void showIncomeTypeFilter() {
        if (mIncomeTypeSelector == null) {
            mIncomeTypeSelector = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    if (options1 < mFilterStatusBeans.size()) {
                        IncomeFilterBean incomeFilterBean = mFilterStatusBeans.get(options1);
                        viewBinding.tvIncomeType.setText(incomeFilterBean.showText);
                        reBuildFilter(currentSelectDate, incomeFilterBean.value);
                    }
                }
            }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_options_default_layout, new CustomListener() {
                @Override
                public void customLayout(View v) {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                    TextView ivCancel = (TextView) v.findViewById(R.id.tv_cancel);
                    tvSubmit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mIncomeTypeSelector.returnData();
                            mIncomeTypeSelector.dismiss();
                        }
                    });
                    ivCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mIncomeTypeSelector.dismiss();
                        }
                    });
                }
            })
                    .setLineSpacingMultiplier(2.5f)
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .setLabels("", "", "")
                    .build();
            mIncomeTypeSelector.setPicker(mFilterStatusBeans);//一级选择器*/
        }
        if (!mIncomeTypeSelector.isShowing()) {
            mIncomeTypeSelector.show();
        }
    }

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