package com.cooleshow.teacher.ui.income;

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

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

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.PopupUtil;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.WithdrawalFilterAdapter;
import com.cooleshow.teacher.adapter.WithdrawalRecordAdapter;
import com.cooleshow.teacher.bean.CourseFilterStatusBean;
import com.cooleshow.teacher.bean.WithdrawalFilterBean;
import com.cooleshow.teacher.bean.WithdrawalRecordBean;
import com.cooleshow.teacher.contract.WithdrawalRecordContract;
import com.cooleshow.teacher.databinding.ActivityWithdrawalRecordBinding;
import com.cooleshow.teacher.presenter.income.WithdrawalRecordPresenter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/24 10:12
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.IncomeCenter.TEACHER_MINE_WITHDRAWAL_RECORD)
public class WithdrawalRecordActivity extends BaseMVPActivity<ActivityWithdrawalRecordBinding, WithdrawalRecordPresenter> implements WithdrawalRecordContract.WithdrawalRecordView, View.OnClickListener {
    private String currentWithdrawalFilterStatus = "ALL";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_date:
                showTimeSelectPicker();
                break;
            case R.id.tv_type:
                initPop(viewBinding.tvType);
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    private WithdrawalRecordAdapter withdrawalRecordAdapter;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "结算记录");
        viewBinding.tvDate.setOnClickListener(this);
        viewBinding.tvType.setOnClickListener(this);

        RecyclerView rvAddress = viewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(manager);
        withdrawalRecordAdapter = new WithdrawalRecordAdapter();
        LayoutInflater inflater = LayoutInflater.from(this);
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        ImageView im_empty_logo = emptyLayout.findViewById(R.id.im_empty_logo);
        im_empty_logo.setBackgroundResource(R.drawable.icon_empty_content);
        withdrawalRecordAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(withdrawalRecordAdapter);
        withdrawalRecordAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

            }
        });
    }

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

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

    private int currentPage;

    @Override
    public void initData() {
        super.initData();
        viewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                queryList(true);
            }
        });
        withdrawalRecordAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryList(false);
                } else {
                    withdrawalRecordAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        currentPage = 1;

        buildDefaultStatusFilterList();
        reBuildFilter(null, "ALL");
        queryList(true);
    }

    private boolean hasNext = true;

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

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

    private ArrayList<WithdrawalFilterBean> mFilterStatusBeans;

    private void buildDefaultStatusFilterList() {
        mFilterStatusBeans = new ArrayList<>();
        mFilterStatusBeans.add(new WithdrawalFilterBean("ALL", "全部"));
        mFilterStatusBeans.add(new WithdrawalFilterBean("DOING", "审核中"));
        mFilterStatusBeans.add(new WithdrawalFilterBean("PASS", "通过"));
        mFilterStatusBeans.add(new WithdrawalFilterBean("UNPASS", "不通过"));
    }

    private TimePickerView pvTime;

    private void showTimeSelectPicker() {
        if (pvTime == null) {
            pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                reBuildFilter(date, currentWithdrawalFilterStatus);
            }).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 Date currentSelectDate;
    private String currentFilterDate;

    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(currentWithdrawalFilterStatus, status)) {
            //防止重复条件触发
            return;
        }
        currentFilterDate = targetDateTimeStr;
        currentWithdrawalFilterStatus = !TextUtils.isEmpty(status) ? status : "WITHDRAWAL";
        currentPage = 1;
        viewBinding.tvDate.setText(currentFilterDate);
        queryList(true);
    }

    private PopupWindow mPopupWindow;
    private WithdrawalFilterAdapter withdrawalFilterAdapter;

    private void initPop(View targetView) {
        if (mPopupWindow == null) {
            View popupContentView = LayoutInflater.from(this).inflate(com.cooleshow.base.R.layout.list_popu_layout, null);
            RecyclerView recyclerView = popupContentView.findViewById(R.id.recyclerView);
            View bg = popupContentView.findViewById(com.cooleshow.base.R.id.view);
            bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                }
            });
            withdrawalFilterAdapter = new WithdrawalFilterAdapter(com.cooleshow.base.R.layout.notice_popu_list_item);
            withdrawalFilterAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    Object object = withdrawalFilterAdapter.getData().get(position);
                    if (object instanceof WithdrawalFilterBean) {
                        if (withdrawalFilterAdapter != null) {
                            withdrawalFilterAdapter.setSelect(position);
                        }
                        WithdrawalFilterBean filterStatusBean = (WithdrawalFilterBean) object;
                        viewBinding.tvType.setText(filterStatusBean.showText);
                        reBuildFilter(currentSelectDate, filterStatusBean.value);
                    }
                    mPopupWindow.dismiss();
                }
            });
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(withdrawalFilterAdapter);
            withdrawalFilterAdapter.setNewInstance(mFilterStatusBeans);
            mPopupWindow = PopupUtil.createNoBackPopupWindow(popupContentView, this, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
        }
        mPopupWindow.showAsDropDown(targetView);
    }

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

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