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

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
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.DeviceBean;
import com.wd.workoffice.bean.SparePartsBean;
import com.wd.workoffice.bean.event.AddDeviceEvent;
import com.wd.workoffice.bean.vo.DeviceRepairVo;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.DeviceRepairProductAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.WorkUtils;

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.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 DeviceBuyRepairProductActivity extends WorkToolBarActivity {
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_machine)
    TextView tvMachine;
    @BindView(R.id.rl_machine)
    RelativeLayout rlMachine;
    @BindView(R.id.tv_spare_parts)
    TextView tvSpareParts;
    @BindView(R.id.rl_spare_parts)
    RelativeLayout rlSpareParts;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_add)
    LinearLayout llAdd;
    @BindView(R.id.et_amount)
    EditText etAmount;
    private Map<String, Object> param;
    private List<DeviceRepairVo> dataList;
    private DeviceRepairProductAdapter dataAdapter;
    private List<DeviceBean.RecordsBean> carList = new ArrayList<>();
    private QMUIDialog.MenuDialogBuilder machineDialog;
    private QMUIDialog.MenuDialogBuilder componentsDialog;
    private QMUIDialog.MenuDialogBuilder sparePartsDialog;
    private List<DeviceBean.RecordsBean> machineList;
    private List<String> machineNameList = new ArrayList<>();
    private List<String> componentsNameList = new ArrayList<>();
    private List<String> sparePartsNameList = new ArrayList<>();
    private DeviceBean.RecordsBean chooseMachine;
    private List<DeviceBean.RecordsBean> componentsList;
    private DeviceBean.RecordsBean chooseComponents;
    private SparePartsBean.RecordsBean chooseSpareParts;
    private List<SparePartsBean.RecordsBean> sparePartsList;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvProduct.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        machineDialog = DialogUtils.listDialog(this);
        componentsDialog = DialogUtils.listDialog(this);
        sparePartsDialog = DialogUtils.listDialog(this);
        WorkUtils.addDecimalsListener(etAmount);
    }


    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        dataAdapter = new DeviceRepairProductAdapter(R.layout.item_device_product_repair, dataList, 0);
        dataAdapter.bindToRecyclerView(rvProduct);
        param = WorkUtils.pageKey();
        param.put("parentId", 0);
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().equipmentNoPageList(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<DeviceBean.RecordsBean> getList = JSON.parseArray(data.getData().toString(), DeviceBean.RecordsBean.class);
                machineList = getList;
                machineNameList.clear();
                for (DeviceBean.RecordsBean device : getList) {
                    machineNameList.add(device.getTitle());
                }
                machineDialog.addItems(machineNameList.toArray(new String[machineNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseMachine = machineList.get(which);
                        tvMachine.setText(machineNameList.get(which));
                        dialog.dismiss();
                        getComponents(chooseMachine.getId());
                        getSparePart(chooseMachine.getId());
                        clearViewData();
                    }
                });
            }
        });
    }

    private void clearViewData() {
        chooseComponents = null;
        chooseSpareParts = null;
        etAmount.setText("");
        tvSpareParts.setText("");
    }

    private void getComponents(int id) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("parentId", id);
        RtfUtils.getRtf().equipmentNoPageList(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<DeviceBean.RecordsBean> getList = JSON.parseArray(data.getData().toString(), DeviceBean.RecordsBean.class);
                componentsList = getList;
                componentsNameList.clear();
                for (DeviceBean.RecordsBean device : getList) {
                    componentsNameList.add(device.getTitle());
                }
                componentsDialog = DialogUtils.listDialog(DeviceBuyRepairProductActivity.this);
                componentsDialog.addItems(componentsNameList.toArray(new String[componentsNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseComponents = componentsList.get(which);
                        etAmount.setText(componentsNameList.get(which));
                        dialog.dismiss();
                    }
                });
            }
        });
    }


    private void getSparePart(int id) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("assetId", id);
        RtfUtils.getRtf().sparePartList(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<SparePartsBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), SparePartsBean.class).getRecords();
                sparePartsList = getList;
                sparePartsNameList.clear();
                for (SparePartsBean.RecordsBean device : getList) {
                    sparePartsNameList.add(device.getItemName());
                }
                sparePartsDialog = DialogUtils.listDialog(DeviceBuyRepairProductActivity.this);
                sparePartsDialog.addItems(sparePartsNameList.toArray(new String[sparePartsNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseSpareParts = sparePartsList.get(which);
                        tvSpareParts.setText(sparePartsNameList.get(which));
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    @Override
    protected void initEvent() {
        dataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                dataList.remove(i);
                dataAdapter.notifyItemRemoved(i);
            }
        });
    }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_next, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.next:
                if (dataList.size() == 0) {
                    toast("请添加产品明细");
                    return super.onOptionsItemSelected(item);
                }
                startActivity(DeviceBuyRepairConfirmActivity.class,
                        "pro", JSON.toJSONString(dataList),
                        "depId", getIntent().getStringExtra("depId"),
                        "depName", getIntent().getStringExtra("depName"),
                        "amount", getIntent().getStringExtra("amount"),
                        "repairDateTimeBegin", getIntent().getStringExtra("repairDateTimeBegin"),
                        "repairDateTimeEnd", getIntent().getStringExtra("repairDateTimeEnd"));

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.tv_add, R.id.rl_machine, R.id.rl_spare_parts, R.id.tv_cancel, R.id.tv_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_machine:
                machineDialog.show();
                break;
            case R.id.rl_spare_parts:
                sparePartsDialog.show();
                break;
            case R.id.tv_cancel:
                clearViewData();
                llAdd.setVisibility(View.GONE);
                break;
            case R.id.tv_ok:
                addData();
                break;
            case R.id.tv_add:
                llAdd.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void addData() {
        String amount = etAmount.getText().toString();
        if (chooseMachine == null) {
            toast("请选择设备");
            return;
        }
        if (TextUtils.isEmpty(amount)||Double.valueOf(amount)==0d) {
            toast("请输入消耗数量");
            return;
        }
        if (chooseSpareParts == null) {
            toast("请选择备件");
            return;
        }
        DeviceRepairVo deviceRepairVo = new DeviceRepairVo();
        deviceRepairVo.setEquipmentId(chooseMachine.getId());
        deviceRepairVo.setEquipmentName(chooseMachine.getTitle());
//        deviceRepairVo.setSubEquipmentId(chooseComponents.getId());
//        deviceRepairVo.setSubEquipmentName(chooseComponents.getTitle());
        deviceRepairVo.setAmount(amount);
        deviceRepairVo.setSparePartId(chooseSpareParts.getId());
        deviceRepairVo.setReplaceSparePartName(chooseSpareParts.getItemName());
        dataList.add(deviceRepairVo);
        dataAdapter.notifyDataSetChanged();
        clearViewData();
        llAdd.setVisibility(View.GONE);
    }


    @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(AddDeviceEvent event) {
        finish();
    }

}
