package com.gingersoft.supply_chain.mvp.ui.fragment.food;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerMeasurementUnitComponent;
import com.gingersoft.supply_chain.mvp.bean.MeasurementUnitBean;
import com.gingersoft.supply_chain.mvp.contract.MeasurementUnitContract;
import com.gingersoft.supply_chain.mvp.presenter.MeasurementUnitPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.MeasurementUnitAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description: 食材單位列表頁面
 */
public class MeasurementUnitFragment extends BaseSupplyChainFragment<MeasurementUnitPresenter> implements MeasurementUnitContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_measurement_unit_list)
    QMUITopBar topbarMeasurementUnitList;
    @BindView(R2.id.ed_measurement_unit_search)
    EditText edMeasurementUnitSearch;
    @BindView(R2.id.btn_measurement_unit_search)
    QMUIAlphaButton btnMeasurementUnitSearch;
    @BindView(R2.id.layout_measurement_unit_search)
    LinearLayout layoutMeasurementUnitSearch;
    @BindView(R2.id.rv_measurement_unit_list)
    RecyclerView rvMeasurementUnitList;
    @BindView(R2.id.btn_new_measurement_unit)
    QMUIAlphaButton btnNewMeasurementUnit;
    @BindView(R2.id.srl_measurement)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R2.id.btn_measurement_unit_confirm)
    QMUIAlphaButton confirmSelect;
    @BindView(R2.id.btn_measurement_unit_cancel)
    QMUIAlphaButton cancelSelect;
    private MeasurementUnitAdapter measurementUnitAdapter;
    /***
     * 編輯或新增單位的回調code
     */
    public final static int EDIT_FOOD_UNIT_REQUEST_CODE = 1001;
    /**
     * 選擇食材單位的回調code
     */
    public final static int SELECT_FOOD_UNIT_REQUEST_CODE = 1002;
    /**
     * 選擇食材單位的數據信息 回調
     */
    public final static String SELECT_FOOD_UNIT_RESULT_DATA = "selectFoodUnit";


    public final static String IS_SELECT_UNIT_KEY = "isSelectUnit";

    private int pageIndex = 0;
    private boolean isSelect = false;

    public static MeasurementUnitFragment newInstance(boolean isSelect) {
        MeasurementUnitFragment fragment = new MeasurementUnitFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_SELECT_UNIT_KEY, isSelect);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMeasurementUnitComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_measurement_unit, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            isSelect = arguments.getBoolean(IS_SELECT_UNIT_KEY);
        }
        confirmSelect.setVisibility(isSelect ? View.VISIBLE : View.GONE);
        cancelSelect.setVisibility(isSelect ? View.VISIBLE : View.GONE);
        btnNewMeasurementUnit.setVisibility(isSelect ? View.GONE : View.VISIBLE);

        initTopBar(topbarMeasurementUnitList, isSelect ? "選擇計量單位" : "計量單位");
        loadInfo("");

        // 重新加载逻辑
        loadService = LoadSir.getDefault().register(smartRefreshLayout, (Callback.OnReloadListener) v -> {
            pageIndex = 0;
            loadInfo("");
        });
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            loadInfo("");
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            loadInfo("");
        });
    }

    private void loadInfo(String unitContent) {
        mPresenter.getMeasurementUnitList(unitContent, pageIndex);
    }

    @OnClick({R2.id.btn_measurement_unit_search, R2.id.btn_new_measurement_unit, R2.id.btn_measurement_unit_confirm, R2.id.btn_measurement_unit_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_new_measurement_unit) {
            //新增計量單位
            startForResult(NewFoodUnitFragment.newInstance(null), EDIT_FOOD_UNIT_REQUEST_CODE);
        } else if (viewId == R.id.btn_measurement_unit_search) {
            //搜索計量單位
            loadInfo(edMeasurementUnitSearch.getText() + "");
        } else if (viewId == R.id.btn_measurement_unit_cancel) {
            killMyself();
        } else if (viewId == R.id.btn_measurement_unit_confirm) {
            Bundle bundle = new Bundle();
            if (measurementUnitAdapter != null) {
                List<MeasurementUnitBean.DataBean.Unit> data = measurementUnitAdapter.getData();
                if (data.size() > 0) {
                    MeasurementUnitBean.DataBean.Unit unit = data.get(measurementUnitAdapter.getSelectIndex());
                    bundle.putSerializable(SELECT_FOOD_UNIT_RESULT_DATA, unit);
                }
            }
            setFragmentResult(SELECT_FOOD_UNIT_REQUEST_CODE, bundle);
            killMyself();
        }
    }

    @Override
    public void loadUnitList(List<MeasurementUnitBean.DataBean.Unit> list) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
        if (list != null && list.size() > 0) {
            loadService.showSuccess();
            smartRefreshLayout.setEnableLoadMore(true);
        } else {
            smartRefreshLayout.setEnableLoadMore(false);
            loadService.showCallback(EmptyCallback.class);
            return;
        }
        if (measurementUnitAdapter == null) {
            measurementUnitAdapter = new MeasurementUnitAdapter(list, isSelect);
            measurementUnitAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                List<MeasurementUnitBean.DataBean.Unit> data = measurementUnitAdapter.getData();
                MeasurementUnitBean.DataBean.Unit unit = data.get(position);
                new AppDialog().showWaringDialog(mContext, "是否確認刪除？", (view1, dialog) -> {
                    dialog.dismiss();
                    mPresenter.deleteMeasurementUnit(unit, position);
                });
            });
            measurementUnitAdapter.setOnItemClickListener((adapter, view, position) -> {
                List<MeasurementUnitBean.DataBean.Unit> data = measurementUnitAdapter.getData();
                MeasurementUnitBean.DataBean.Unit unit = data.get(position);
                startForResult(NewFoodUnitFragment.newInstance(unit), EDIT_FOOD_UNIT_REQUEST_CODE);
            });
            rvMeasurementUnitList.setAdapter(measurementUnitAdapter);
        } else {
            measurementUnitAdapter.setList(list);
        }
    }

    @Override
    public void deleteSuccess(int position) {
        measurementUnitAdapter.removeAt(position);
        if (measurementUnitAdapter.getData().size() == 0) {
            loadService.showCallback(EmptyCallback.class);
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        loadInfo("");
    }
}
