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

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.alibaba.fastjson.JSONObject;
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.ProPriceBean;
import com.wd.workoffice.bean.TicketAddBean;
import com.wd.workoffice.bean.TicketDetailBean;
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.store.StoreSaleCarActivity;
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 WorkChooseProductActivity 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<TicketAddBean.RecordsBean> clientList;
    private WorkAddTicketOrderAdapter clientAdapter;
    private int page = 1;
    private List<TicketAddBean.RecordsBean> carList = new ArrayList<>();

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


    private void openDialog(TicketAddBean.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 (TicketAddBean.RecordsBean recordsBean : carList) {
            if (data.getId() == recordsBean.getId()) {
                etPrice.setText(recordsBean.getCarPrice());
                num.setNumber(recordsBean.getCarNum());
            }
        }
        num.setMaxNum(data.getCanInvoiceSum());
        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(clientList.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(TicketAddBean.RecordsBean chooseProduct, String number, String price) {
        boolean isHas = false;
        for (TicketAddBean.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 WorkAddTicketOrderAdapter(R.layout.item_ticket_add_detail, clientList);
        clientAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("current", 1);
        if (TextUtils.isEmpty(getIntent().getStringExtra("supplier"))) {
            param.put("customerId", getIntent().getStringExtra("customerId"));
            param.put("launchDeptId", getIntent().getStringExtra("depId"));
        } else {
            param.put("supplierId", getIntent().getStringExtra("customerId"));
            param.put("receiveDeptId", getIntent().getStringExtra("depId"));
        }

        getData();
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.isEmpty(getIntent().getStringExtra("supplier"))) {
            if (TextUtils.equals("销售订单", getIntent().getStringExtra("orderType"))) {
                observable = RtfUtils.getRtf().saleTicketOrder(param);
            } else if (TextUtils.equals("组装订单", getIntent().getStringExtra("orderType"))) {
                observable = RtfUtils.getRtf().packageTicketOrder(param);
            } else if (TextUtils.equals("外采购订单", getIntent().getStringExtra("orderType"))) {
                observable = RtfUtils.getRtf().purchaseTicketOrder(param);
            } else {
                observable = RtfUtils.getRtf().crucibleTicketOrder(param);
            }
        } else {
            if (TextUtils.equals("供应订单", getIntent().getStringExtra("orderType"))) {
                observable = RtfUtils.getRtf().supplierTicketOrder(param);
            } else if (TextUtils.equals("外采购订单", getIntent().getStringExtra("orderType"))) {
                observable = RtfUtils.getRtf().purchaseOutTicketOrder(param);
            } else {
                observable = RtfUtils.getRtf().supplierTicketOrder(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<TicketAddBean.RecordsBean> dataList = JSON.parseObject(data.getData().toString(), TicketAddBean.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_work_choose_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;
                }
                if (TextUtils.isEmpty(getIntent().getStringExtra("supplier"))) {
                    startActivity(WorkFinancialTicketSubmitActivity.class, "orderType", getIntent().getStringExtra("orderType"),
                            "depId", getIntent().getStringExtra("depId"), "customerId", getIntent().getStringExtra("customerId"),
                            "customerName", getIntent().getStringExtra("customerName"),
                            "info", JSON.toJSONString(carList));
                } else {
                    startActivity(WorkFinancialReceiveTicketSubmitActivity.class, "orderType", getIntent().getStringExtra("orderType"),
                            "depId", getIntent().getStringExtra("depId"), "customerId", getIntent().getStringExtra("customerId"),
                            "customerName", getIntent().getStringExtra("customerName"),
                            "info", JSON.toJSONString(carList));
                }


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