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

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

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.common.loadsir.ErrorCallback;
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.DaggerSupplierListComponent;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.contract.SupplierListContract;
import com.gingersoft.supply_chain.mvp.presenter.SupplierListPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SupplierAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodIngredientsFragment;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description: 供應商列表， 選擇供應商
 */
public class SupplierListFragment extends BaseSupplyChainFragment<SupplierListPresenter> implements SupplierListContract.View, View.OnClickListener {
    public final static int SELECT_SUPPLIER_RESULTCODE = 1001;
    public final static String SELECT_SUPPLIER_DATA = "supplier_data";

    @BindView(R2.id.topbar_supplier_list)
    QMUITopBar mTopBarSupplierList;
    @BindView(R2.id.rv_supplier_list)
    RecyclerView rvSupplierList;
    @BindView(R2.id.btn_new_supplier)
    QMUIAlphaTextView btnNewSupplier;
    @BindView(R2.id.ed_supplier_search)
    EditText edSupplier;
    public final static int SUPPLIER_LIST = 101;
    private SupplierAdapter supplierAdapter;
    @BindView(R2.id.srl_supplier)
    SmartRefreshLayout smartRefreshLayout;
    /**
     * 當{@Link isSelect}為true時，顯示這兩個按鈕
     */
    @BindView(R2.id.btn_supplier_confirm)
    QMUIAlphaTextView btnConfirm;
    @BindView(R2.id.btn_supplier_cancel)
    QMUIAlphaTextView btnCancel;

    private int pageIndex = 0;
    /**
     * 是否是選擇供應商
     */
    private boolean isSelect = false;
    public static final String IS_SELECT_KEY = "selectSupplier";
    private static final String SUPPLIER_NAME_KEY = "supplierNameKey";

    public static SupplierListFragment newInstance(boolean isSelect, String supplierName) {
        SupplierListFragment fragment = new SupplierListFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_SELECT_KEY, isSelect);
        bundle.putString(SUPPLIER_NAME_KEY, supplierName);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerSupplierListComponent //如找不到该类,请编译一下项目
                .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_supplier_list, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        smartRefreshLayout.setPrimaryColorsId(R.color.trans, R.color.black);

        Bundle arguments = getArguments();
        if (arguments != null) {
            isSelect = arguments.getBoolean(IS_SELECT_KEY);
            mPresenter.setSupplierName(arguments.getString(SUPPLIER_NAME_KEY));
        }
        btnConfirm.setVisibility(isSelect ? View.VISIBLE : View.GONE);
        btnCancel.setVisibility(isSelect ? View.VISIBLE : View.GONE);
        btnNewSupplier.setVisibility(isSelect ? View.GONE : View.VISIBLE);

        loadService = LoadSir.getDefault().register(smartRefreshLayout, (Callback.OnReloadListener) v -> {
            // 重新加载逻辑
            pageIndex = 0;
            getSupplierList();
        });
        initTopBar();
        getSupplierList();

        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 0;
            getSupplierList();
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getSupplierList();
        });
        initEditText();
    }

    private void initEditText() {
        edSupplier.setOnEditorActionListener((v, actionId, event) -> {
            if (event != null) {
                return true;
            }
            return false;
        });
    }

    private void getSupplierList() {
        if (supplierAdapter == null) {
            mPresenter.getSupplierList(edSupplier.getText() + "", pageIndex, isSelect);
        } else {
            mPresenter.getSupplierList(edSupplier.getText() + "", pageIndex, isSelect && supplierAdapter.getSelectIndex() == -1);
        }
    }

    private void initTopBar() {
        initTopBar(mTopBarSupplierList, "供應商");
        if (mTopBarSupplierList.getLeftViewList().size() <= 0) {
            mTopBarSupplierList.addRightImageButton(R.drawable.ic_screen, R.id.topbar_right_screen_button).setOnClickListener(this);
        }
    }

    @OnClick({R2.id.btn_new_supplier, R2.id.btn_supplier_search, R2.id.btn_supplier_confirm, R2.id.btn_supplier_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.topbar_right_screen_button) {
            //篩選

        } else if (viewId == R.id.btn_new_supplier) {
            //新增供應商
            startForResult(NewSupplierFragment.newInstance(null), SUPPLIER_LIST);
        } else if (viewId == R.id.btn_supplier_search) {
            //搜索供應商
            pageIndex = 0;
            getSupplierList();
        } else if (viewId == R.id.btn_supplier_cancel) {
            killMyself();
        } else if (viewId == R.id.btn_supplier_confirm) {
            //選擇供應商後，確認
            if (supplierAdapter != null) {
                List<SupplierInfoBean> data = supplierAdapter.getData();
                int selectIndex = supplierAdapter.getSelectIndex();
                if (data.size() > 0 && selectIndex < data.size() && selectIndex >= 0) {
                    SupplierInfoBean supplierInfoBean = data.get(selectIndex);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(SELECT_SUPPLIER_DATA, supplierInfoBean);
                    setFragmentResult(SELECT_SUPPLIER_RESULTCODE, bundle);
                    killMyself();
                } else {
                    showMessage("請選擇供應商");
                }
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == SUPPLIER_LIST && resultCode == RESULT_OK) {
            //新增或編輯了供應商，重新獲取所有供應商數據
            pageIndex = 0;
            getSupplierList();
        }
    }

    @Override
    public void loadSupplierList(@NotNull List<SupplierInfoBean> supplierBeanList) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
        if (supplierBeanList.size() == 0) {
            loadService.showCallback(EmptyCallback.class);
            smartRefreshLayout.setEnableLoadMore(false);
            return;
        } else {
            loadService.showSuccess();
            smartRefreshLayout.setEnableLoadMore(true);
        }
        if (supplierAdapter == null) {
            supplierAdapter = new SupplierAdapter(supplierBeanList, isSelect);
            rvSupplierList.setAdapter(supplierAdapter);

            supplierAdapter.setOnItemClickListener((adapter, view, position) -> {
                List<SupplierInfoBean> data = supplierAdapter.getData();
                startForResult(NewSupplierFragment.newInstance(data.get(position)), SUPPLIER_LIST);
            });
            supplierAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_supplier_delete) {
                    new AppDialog().showWaringDialog(mContext, "刪除供應商", (view1, dialog) -> {
                        dialog.dismiss();
                        List<SupplierInfoBean> data = supplierAdapter.getData();
                        mPresenter.deleteSupplier(data.get(position).getId(), position);
                    });
                } else if (view.getId() == R.id.layout_supplier_food_info) {
                    //跳轉到供應商食品詳情
                    List<SupplierInfoBean> data = supplierAdapter.getData();
                    start(FoodIngredientsFragment.newInstance(data.get(position).getId(), data.get(position).getSupplierName()));
                }
            });
        } else {
            supplierAdapter.setList(supplierBeanList);
        }
    }

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

    @Override
    public void loadError() {
        loadService.showCallback(ErrorCallback.class);
    }

    @Override
    public void setSelectIndex(int index) {
        if (supplierAdapter != null) {
            supplierAdapter.setSelectIndex(index);
        }
    }
}
