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.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.alibaba.android.arouter.launcher.ARouter;
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.common.WebConstants;
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.IncomeFilterAdapter;
import com.cooleshow.teacher.adapter.MineIncomeAdapter;
import com.cooleshow.teacher.bean.AccountDetailBean;
import com.cooleshow.teacher.bean.CourseFilterStatusBean;
import com.cooleshow.teacher.bean.IncomeFilterBean;
import com.cooleshow.teacher.bean.UserAccountBean;
import com.cooleshow.teacher.contract.MineIncomeContract;
import com.cooleshow.teacher.databinding.ActivityMineIncomeBinding;
import com.cooleshow.teacher.presenter.income.MineIncomePresenter;
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/23 14:06
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.IncomeCenter.TEACHER_MINE_INCOME)
public class MineIncomeActivity extends BaseMVPActivity<ActivityMineIncomeBinding, MineIncomePresenter> implements MineIncomeContract.MineIncomeView, View.OnClickListener {
    private String currentIncomeFilterStatus = "";
    private OptionsPickerView mIncomeTypeSelector;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right_text:
                ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.TEACHER_INCOME)
                        .navigation();
                break;
            case R.id.tv_date:
                showTimeSelectPicker();
                break;
            case R.id.tv_income_type:
//                initPop(viewBinding.tvIncomeType);
                showIncomeTypeFilter();
                break;
            case R.id.tv_withdrawal:
                ARouter.getInstance().build(RouterPath.IncomeCenter.TEACHER_MINE_WITHDRAWAL)
                        .navigation();
                break;
        }

    }

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

    private MineIncomeAdapter mineIncomeAdapter;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "我的收入");
        viewBinding.toolbarInclude.tvRightText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.common_black));
        viewBinding.toolbarInclude.tvRightText.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRightText.setText("收入统计");
        viewBinding.toolbarInclude.tvRightText.setOnClickListener(this);
        viewBinding.tvDate.setOnClickListener(this);
        viewBinding.tvIncomeType.setOnClickListener(this);
        viewBinding.tvWithdrawal.setOnClickListener(this);
        RecyclerView rvAddress = viewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvAddress.setLayoutManager(manager);
        mineIncomeAdapter = new MineIncomeAdapter();
        LayoutInflater inflater = LayoutInflater.from(this);
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        mineIncomeAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(mineIncomeAdapter);
        mineIncomeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

            }
        });
    }

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

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

    private int currentPage;


    @Override
    protected void onResume() {
        super.onResume();
        presenter.getUserAccountDetail();
    }

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

        buildDefaultStatusFilterList();
        reBuildFilter(null, "");
    }

    private ArrayList<IncomeFilterBean> mFilterStatusBeans;

    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", "会员分润"));
        mFilterStatusBeans.add(new IncomeFilterBean("MALL_SHARE", "商品分润"));

    }

    private boolean hasNext = true;

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

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


    @Override
    public void userAccountDetailSuccess(AccountDetailBean data) {
        if (null == data) {
            return;
        }
        viewBinding.tvBalance.setText(data.amountUsable + "");
    }

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

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

    private TimePickerView pvTime;

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

    private PopupWindow mPopupWindow;
    private IncomeFilterAdapter incomeFilterAdapter;


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

    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();
                    }
                }
            });
            incomeFilterAdapter = new IncomeFilterAdapter(com.cooleshow.base.R.layout.notice_popu_list_item);
            incomeFilterAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    Object object = incomeFilterAdapter.getData().get(position);
                    if (object instanceof IncomeFilterBean) {
                        if (incomeFilterAdapter != null) {
                            incomeFilterAdapter.setSelect(position);
                        }
                        IncomeFilterBean filterStatusBean = (IncomeFilterBean) object;
                        viewBinding.tvIncomeType.setText(filterStatusBean.showText);
                        reBuildFilter(currentSelectDate, filterStatusBean.value);
                    }
                    mPopupWindow.dismiss();
                }
            });
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(incomeFilterAdapter);
            incomeFilterAdapter.setNewInstance(mFilterStatusBeans);
            mPopupWindow = PopupUtil.createNoBackPopupWindow(popupContentView, this, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
        }
        mPopupWindow.showAsDropDown(targetView);
    }
}
