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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.AddStockChooseBean;
import com.wd.workoffice.bean.FareOrderBean;
import com.wd.workoffice.bean.ProAddBean;
import com.wd.workoffice.bean.ProcessBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.StockBean;
import com.wd.workoffice.bean.TradingBean;
import com.wd.workoffice.bean.event.CheckTicketEvent;
import com.wd.workoffice.bean.event.FareConfirmEvent;
import com.wd.workoffice.bean.event.ModifyCarEvent;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.presenter.BatChooseInfoPresenter;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.order.ProductOrderProTargetActivity;
import com.wd.workoffice.ui.activity.bat.store.ChooseProcessActivity;
import com.wd.workoffice.ui.activity.bat.store.ChooseStockActivity;
import com.wd.workoffice.ui.activity.bat.store.StoreSaleClientActivity;
import com.wd.workoffice.ui.adapter.FareOrderAdapter;
import com.wd.workoffice.ui.adapter.StoreProductAdapter;
import com.wd.workoffice.ui.adapter.TradingProDetailAdapter;
import com.wd.workoffice.ui.adapter.TradingProductAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.BadgeCarProvider;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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 io.reactivex.disposables.Disposable;

/**
 * 新增运费单
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class FareAddActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;
    @BindView(R.id.tv_client)
    TextView tvClient;
    @BindView(R.id.ll_client)
    LinearLayout llClient;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_product)
    RecyclerView rvData;
    private Map<String, Object> param;
    private List<FareOrderBean.RecordsBean> proList;
    private FareOrderAdapter proAdapter;
    private int page = 1;
    private Integer clientId;

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

    @Override
    protected void initData() {
        proList = new ArrayList<>();
        proAdapter = new FareOrderAdapter(R.layout.item_fare_order, proList, 0);
        proAdapter.bindToRecyclerView(rvData);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvData);
        param = WorkUtils.pageKey();
        param.put("current", 1);
    }


    @Override
    protected void initEvent() {
        proAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                param.put("current", page);
                getData();
            }
        }, rvData);
    }


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


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (resultCode == 10001) {
                    String clientName = data.getStringExtra("clientName");
                    clientId = data.getIntExtra("id", 0);
                    tvClient.setText(clientName);
                    param.put("customerId", clientId);
                    page = 1;
                    param.put("current", 1);
                    getData();
                    break;
                }
        }
    }


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

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ModifyCarEvent event) {
        changeNumAndPrice();
    }

    private void changeNumAndPrice() {
        Map<Integer, Boolean> isChoose = proAdapter.getIsChoose();
        int chooseNum = 0;
        for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
            if (entry.getValue()) {
                chooseNum += 1;
            }
        }
        tvNum.setText(String.format("共选中 %s 条", chooseNum));
    }

    @OnClick({R.id.ll_client, R.id.tv_ok, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_client:
                startActivityForResult(StoreSaleClientActivity.class, 10001,
                        "depId", UserKeeper.getInstance().getUserDepId(),
                        "code", "CUSTOMER");
                break;
            case R.id.tv_ok:
                Map<Integer, Boolean> isChoose = proAdapter.getIsChoose();
                if (isChoose.entrySet().size() == 0) {
                    toast("请选择订单");
                    return;
                }
                List<FareOrderBean.RecordsBean> addList = new ArrayList<>();
                for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
                    if (entry.getValue()) {
                        addList.add(proList.get(entry.getKey()));
                    }
                }
                startActivity(FareAddConfirmActivity.class,
                        "customerId", clientId.toString(),
                        "data", JSON.toJSONString(addList));
                break;
            case R.id.btn_search:
                param.put("orderId", etKey.getText().toString());
                param.put("current", 1);
                page = 1;
                getData();
                break;
        }
    }

    private void getData() {
        RtfUtils.getRtf().logisticsList(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<FareOrderBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), FareOrderBean.class).getRecords();
                if (page == 1) {
                    proList.clear();
                    proList.addAll(getList);
                    proAdapter.initChoose();
                    proAdapter.notifyDataSetChanged();
                    proAdapter.loadMoreComplete();
                } else {
                    proAdapter.loadMoreComplete();
                    proList.addAll(getList);
                    proAdapter.notifyDataSetChanged();
                }
                if (proList.size() == 0) {
                    proAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }

    @Subscribe
    public void refresh(FareConfirmEvent event) {
        finish();
    }
}
