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

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.TicketAddBean;
import com.wd.workoffice.bean.event.CheckTicketEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.work.WorkFinancialReceiveTicketSubmitActivity;
import com.wd.workoffice.ui.activity.bat.work.WorkFinancialTicketSubmitActivity;
import com.wd.workoffice.ui.adapter.ProTargetAddAdapter;
import com.wd.workoffice.ui.adapter.WorkAddTicketOrderAdapter;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.AddAndReduceView;

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

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

import androidx.appcompat.app.AlertDialog;
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.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 选择目标产品
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class ProductOrderProTargetActivity 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.et_key)
    EditText etKey;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private Map<String, Object> param;
    private List<ProductBean.RecordsBean> clientList;
    private ProTargetAddAdapter clientAdapter;
    private int page = 1;
    private List<ProductBean.RecordsBean> carList = new ArrayList<>();

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


    private void openDialog(ProductBean.RecordsBean data, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_add_cart, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        tvDesc.setText("组装单价");
        AddAndReduceView num = view.findViewById(R.id.ar_num);
        EditText etPrice = view.findViewById(R.id.et_price);
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
                etPrice.setText(recordsBean.getCarPrice());
                num.setNumber(recordsBean.getCarNum());
            }
        }
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etPrice.getText().toString())) {
                    toast("请填写组装单价");
                    return;
                }
                clientList.get(position).setCarNum(num.getNumber());
                clientList.get(position).setCarPrice(etPrice.getText().toString());
                clientAdapter.notifyItemChanged(position);
                addCart(data, num.getNumber(), etPrice.getText().toString());
                tvNum.setText("共 ".concat(carList.size() + "").concat(" 件"));
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    /**
     * 添加购物车
     *
     * @param chooseProduct 产品
     * @param number        数量
     * @param price         单价
     */
    private void addCart(ProductBean.RecordsBean chooseProduct, String number, String price) {
        boolean isHas = false;
        for (ProductBean.RecordsBean recordsBean : carList) {
            if (chooseProduct.getId() == recordsBean.getId()) {
                isHas = true;
                recordsBean.setCarNum(number);
                recordsBean.setCarPrice(price);
            }
        }
        if (!isHas) {
            chooseProduct.setCarNum(number);
            chooseProduct.setCarPrice(price);
            carList.add(chooseProduct);
        }
        toast("加入购物车成功");
    }

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new ProTargetAddAdapter(R.layout.item_product_target_pro, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        param.put("transitPartId", getIntent().getStringExtra("customerId"));
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().saleOrderTargetPro(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<ProductBean.RecordsBean> dataList = JSON.parseObject(data.getData().toString(), ProductBean.class).getRecords();
                if (page == 1) {
                    clientList.clear();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                    clientAdapter.loadMoreComplete();
                } else {
                    clientAdapter.loadMoreComplete();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                }
                if (dataList.size() == 0) {
                    clientAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        clientAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                param.put("current", page);
                getData();
            }
        }, rvProduct);
        clientAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                openDialog(clientList.get(position), position);
            }
        });
    }

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


    @OnClick({R.id.tv_ok, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ok:
                if (carList.size() == 0) {
                    toast("购物车没有产品");
                    return;
                }
                startActivity(ProductConfirmActivity.class,
                        "base",getIntent().getStringExtra("base"),
                        "usedStockId", getIntent().getStringExtra("usedStockId"),
                        "targetStockId", getIntent().getStringExtra("targetStockId"),
                        "customerId", getIntent().getStringExtra("customerId"),
                        "to", JSON.toJSONString(carList),
                        "from", getIntent().getStringExtra("from"));
                break;
            case R.id.btn_search:
                param.put("name", etKey.getText().toString());
                param.put("current", 1);
                page = 1;
                getData();
                break;
        }
    }

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

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

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