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

import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
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.WorkToolBarActivity;
import com.wd.workoffice.bean.ReturnApplyBean;
import com.wd.workoffice.bean.event.CheckMoneytEvent;
import com.wd.workoffice.bean.event.CheckReturnEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.RetrunSendApplyAdapter;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
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 flexible.xd.android_base.network.rtfhttp.Transformer;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

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

    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;
    private Map<String, Object> param;
    private List<ReturnApplyBean.RecordsBean> dataList;
    private RetrunSendApplyAdapter dataAdapter;
    private int page = 1;
    private String orderType;

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


    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        dataList = new ArrayList<>();
        dataAdapter = new RetrunSendApplyAdapter(R.layout.item_return_apply, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        param = WorkUtils.pageKey();
        page = 1;
        param.put("current", page);
        param.put("orderId", getIntent().getStringExtra("orderId"));
        param.put("productId", getIntent().getStringExtra("productId"));
        getData();
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().returnApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().returnPoApplyList(param);
        } else {
            observable = RtfUtils.getRtf().returnApplyList(param);
        }
        observable.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<ReturnApplyBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), ReturnApplyBean.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(ReturnDetailActivity.class,
                        "info", JSON.toJSONString(dataList.get(position)),
                        "orderType", orderType
                        , "status", getIntent().getStringExtra("status")
                        , "id", getIntent().getStringExtra("orderId")
                        , "identity", getIntent().getStringExtra("identity"));
            }
        });
    }

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


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void refresh(CheckReturnEvent event) {
        page = 1;
        param.put("current", page);
        getData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String orderType = getIntent().getStringExtra("orderType");
        String num = getIntent().getStringExtra("num");
        if (Double.valueOf(num) == 0d) {
            return super.onCreateOptionsMenu(menu);
        }
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            if (WorkUtils.hasPermission(PagePermissionType.SO_RETURN_SAVE.getPermission())) {
                getMenuInflater().inflate(R.menu.menu_add, menu);
            }
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            if (WorkUtils.hasPermission(PagePermissionType.PO_RETURN_SAVE.getPermission())) {
                getMenuInflater().inflate(R.menu.menu_add, menu);
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                startActivity(ReturnAddActivity.class,
                        "returnNum", getIntent().getStringExtra("returnNum"),
                        "orderType", getIntent().getStringExtra("orderType"),
                        "productId", getIntent().getStringExtra("productId"),
                        "orderItemId", getIntent().getStringExtra("orderItemId"),
                        "enterStockType", getIntent().getStringExtra("enterStockType"),
                        "deptId", getIntent().getStringExtra("deptId"),
                        "id", getIntent().getStringExtra("orderId"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
