package com.wd.workoffice.ui.activity.bat.work;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.Config;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.StockFlowBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.FilterBaseAdapter;
import com.wd.workoffice.ui.adapter.WorkStockFlowAdapter;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.disposables.Disposable;

/**
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class WorkWarehouseStockFlowActivity extends WorkToolBarActivity {

    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    private Map<String, Object> param;
    private List<StockFlowBean.RecordsBean> dataList;
    private WorkStockFlowAdapter dataAdapter;
    private int page = 1;
    private QMUIPopup popup;
    private FilterBaseAdapter filterBaseAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }


    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        dataAdapter = new WorkStockFlowAdapter(R.layout.item_stock_flow, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        filterBaseAdapter = new FilterBaseAdapter(Config.STOCK_FLOW_TYPE);
        popup = topPopInit(this);
        param = WorkUtils.pageKey();
        param.put("sqId", getIntent().getStringExtra("id"));
        param.put("current", page);

        getData();
    }

    private void getData() {
        RtfUtils.getRtf().stockFlow(param).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                List<StockFlowBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), StockFlowBean.class).getRecords();

                if (page == 1) {
                    srlRefresh.finishRefresh();
                    dataList.clear();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                    dataAdapter.loadMoreComplete();
                } else {
                    dataAdapter.loadMoreComplete();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                }
                if (getList.size() == 0) {
                    dataAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }


    @Override
    protected void initEvent() {
        srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                param.put("current", page);
                getData();
            }
        });
        dataAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                param.put("current", page);
                getData();
            }
        }, rvData);
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(WorkWarehouseStockFlowDetailActivity.class, "detail", JSON.toJSONString(dataList.get(position)));
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_work_stock_flow;
    }

    public QMUIPopup topPopInit(Context context) {
        popup = QMUIPopups.listPopup(context,
                ViewGroup.LayoutParams.MATCH_PARENT,
                QMUIDisplayHelper.dp2px(context, 300), filterBaseAdapter
                ,
                (parent, view, position, id) -> {
                    filterBaseAdapter.setChoosePos(position);
                    filterBaseAdapter.notifyDataSetChanged();
                    tvType.setText(Config.STOCK_FLOW_TYPE.get(position));
                    popup.dismiss();
                    page = 1;
                    param.put("current", page);
                    param.put("type", Config.STOCK_FLOW_TYPE_CODE.get(position));
                    getData();
                })
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                .shadow(true)
                .edgeProtection(QMUIDisplayHelper.dp2px(context, 10))
                .offsetYIfTop(QMUIDisplayHelper.dp2px(context, 5));
        return popup;
    }


    @OnClick({R.id.tv_type, R.id.tv_start, R.id.tv_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_type:
                popup.show(tvType);
                break;
            case R.id.tv_start:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        param.put("searchStartTime", time + " 00:00:00");
                        tvStart.setText(time);
                        page = 1;
                        param.put("current", page);
                        getData();
                    }
                },false).show();
                break;
            case R.id.tv_end:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        param.put("searchEndTime", time + " 23:59:59");
                        tvEnd.setText(time);
                        page = 1;
                        param.put("current", page);
                        getData();
                    }
                },false).show();
                break;
        }
    }
}
