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

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
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.DaggerFoodUnitPageComponent;
import com.gingersoft.supply_chain.mvp.bean.BasicUnitBean;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.contract.FoodUnitPageContract;
import com.gingersoft.supply_chain.mvp.presenter.FoodUnitPagePresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.BasicUnitAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.DeputyUnitAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.utils.NotDispatchListener;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogView;
import com.qmuiteam.qmui.widget.popup.QMUIBasePopup;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description: 最新版食品單位填寫頁面
 */
public class FoodUnitPageFragment extends BaseSupplyChainFragment<FoodUnitPagePresenter> implements FoodUnitPageContract.View, NotDispatchListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar topBar;
    @BindView(R2.id.ed_basic_unit)
    EditText edBasicUnit;
    @BindView(R2.id.rv_deputy_unit_list)
    RecyclerView rvDeputyUnitList;
    @BindView(R2.id.rv_basic_unit_list)
    RecyclerView rvBasicUnitList;
    @BindView(R2.id.tv_food_unit_complete)
    QMUIAlphaTextView tvFoodUnitComplete;

    private DeputyUnitAdapter deputyUnitAdapter;

    private BasicUnitAdapter basicUnitAdapter;
    /**
     * 主單位名稱
     */
    public final static String BASIC_UNIT_KEY = "basicUnitKey";
    /**
     * 副單位集合
     */
    public final static String DEPUTY_UNIT_KEY = "deputyUnitKey";
    /**
     * 是否是修改單位
     */
    public final static String UPDATE_UNIT_KEY = "updateUnitKey";
    /**
     * 食品id
     */
    public final static String FOOD_ID_KEY = "foodIdKey";

    /**
     * @param basicUnit       基本單位
     * @param deputyUnitBeans 副單位集合
     * @return
     */
    public static FoodUnitPageFragment newInstance(String basicUnit, List<DeputyUnitBean> deputyUnitBeans, boolean isUpdateUnit, Integer foodId) {
        FoodUnitPageFragment fragment = new FoodUnitPageFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DEPUTY_UNIT_KEY, (Serializable) deputyUnitBeans);
        bundle.putString(BASIC_UNIT_KEY, basicUnit);
        bundle.putBoolean(UPDATE_UNIT_KEY, isUpdateUnit);
        if (foodId != null) {
            bundle.putInt(FOOD_ID_KEY, foodId);
        }
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.initData(getArguments());
        edBasicUnit.requestFocus();
    }

    @OnClick({R2.id.tv_add_deputy, R2.id.tv_food_unit_complete})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.tv_add_deputy) {
            //添加副單位
            mPresenter.addDeputyUnit();
        } else if (viewId == R.id.tv_food_unit_complete) {
            //添加單位完成，將副單位列表和主單位名稱傳回去
            //拿到主單位
            String basicUnit = edBasicUnit.getText() + "";
            if (TextUtil.isEmptyOrNullOrUndefined(basicUnit)) {
                showMessage("請輸入基本單位");
                edBasicUnit.setError("請輸入基本單位");
                return;
            }
            if (deputyUnitAdapter != null && deputyUnitAdapter.getItemCount() > 0) {
                mPresenter.addDeputyUnit(deputyUnitAdapter.getData());
            } else {
                mPresenter.addDeputyUnit(null);
            }
        }
    }

    @Override
    public void loadBasicUnitAdapter(List<BasicUnitBean> basicUnitBeans) {
        basicUnitAdapter = new BasicUnitAdapter(basicUnitBeans);
        //獲取到基礎單位之後，才在標題欄中添加刪除按鈕
        topBar.addRightImageButton(R.drawable.ic_white_delete,R.id.btn_delete).setOnClickListener(v -> {
            //刪除
            basicUnitAdapter.toggleDelete();
        });
        rvBasicUnitList.setLayoutManager(new GridLayoutManager(mContext, 5));
        rvBasicUnitList.setAdapter(basicUnitAdapter);
        basicUnitAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position == basicUnitAdapter.getItemCount() - 1) {
                //新增
                AppDialog.getInstance().showEditDialog(mContext, "新增單位", "單位名稱：", "", "", new AppDialog.OnInputConfirmListener() {
                    @Override
                    public void onConfirm(String text) {
                        if (TextUtil.isNotEmptyOrNullOrUndefined(text)) {
                            mPresenter.addBasicUnit(text, basicUnitAdapter.getData());
                        }
                    }
                });
            } else {
                //先獲取當前焦點在哪個輸入框上，然後再填充內容
                FragmentActivity activity = getActivity();
                if (activity != null) {
                    Window window = activity.getWindow();
                    if (window != null) {
                        View decorView = window.getDecorView();
                        View focusView = decorView.findFocus();
                        if (focusView instanceof EditText) {
                            EditText editText = (EditText) focusView;
                            editText.setText(basicUnitAdapter.getData().get(position).getContent());
                            editText.setSelection(editText.getText().length());
                        }
                    }
                }
            }
        });

        basicUnitAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if(view.getId() == R.id.iv_delete_basic_unit){
                //刪除單位
                mPresenter.deleteUnitKey(basicUnitAdapter.getItem(position).getId(), position);
            }
        });
    }

    @Override
    public void addBasicUnit(BasicUnitBean basicUnitBean) {
        if (basicUnitAdapter != null) {
            int index = basicUnitAdapter.getItemCount() - 1;
            basicUnitAdapter.addData(Math.max(index, 0), basicUnitBean);
        }
    }

    @Override
    public void loadDeputyUnitAdapter(List<DeputyUnitBean> deputyUnitBeans) {
        if (deputyUnitAdapter == null) {
            deputyUnitAdapter = new DeputyUnitAdapter(deputyUnitBeans);
            rvDeputyUnitList.setAdapter(deputyUnitAdapter);
            deputyUnitAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_deputy_unit_delete) {
                    //刪除副單位
                    mPresenter.deleteDeputyUnit(deputyUnitAdapter.getItem(position), position);
                }
            });
        } else {
            deputyUnitAdapter.setList(deputyUnitBeans);
        }
    }

    @Override
    public void initTopBar(String title) {
        initTopBar(topBar, title);
    }

    @Override
    public void setMainUnit(String content) {
        edBasicUnit.setText(content);
    }

    @Override
    public void callBackDeputyUnit(List<DeputyUnitBean> deputyUnitBeans) {
        String basicUnit = edBasicUnit.getText() + "";

        Bundle result = new Bundle();
        result.putString(BASIC_UNIT_KEY, basicUnit);
        if (deputyUnitBeans != null) {
            result.putSerializable(DEPUTY_UNIT_KEY, (Serializable) deputyUnitBeans);
        }
        setFragmentResult(RESULT_OK, result);
        killMyself();
    }

    @Override
    public void deleteDeputyUnit(int position) {
        deputyUnitAdapter.removeAt(position);
    }

    @Override
    public void deleteUnitKey(int position) {
        basicUnitAdapter.removeAt(position);
    }
}
