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

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.MultiSelectBean;
import com.gingersoft.gsa.cloud.ui.adapter.multi.InfoMultiAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
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.DaggerNewFoodIngredientsComponent;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.contract.NewFoodIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.NewFoodIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment;
import com.gingersoft.supply_chain.mvp.utils.SelectPicture;
import com.jess.arms.di.component.AppComponent;
import com.permissionx.guolindev.PermissionX;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration.VERTICAL_LIST;
import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_CATEGORY_DATA_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_FOOD_CATEGORY_REQUEST_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodUnitPageFragment.BASIC_UNIT_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodUnitPageFragment.DEPUTY_UNIT_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.PackageSpecificationFragment.SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment.SELECT_SUPPLIER_DATA;
import static com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment.SELECT_SUPPLIER_RESULTCODE;
import static com.yalantis.ucrop.UCrop.REQUEST_CROP;


/**
 * ================================================
 * Description: 新增食材、編輯食材
 *
 * @author admin
 */
public class NewFoodIngredientsFragment extends BaseSupplyChainFragment<NewFoodIngredientsPresenter> implements NewFoodIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_new_food_ingredients)
    QMUITopBar topbarNewFoodIngredients;
    @BindView(R2.id.btn_save_new_food_ingredients)
    QMUIAlphaButton btnSaveNewFoodIngredients;
    @BindView(R2.id.rv_new_food_ingredients)
    RecyclerView rvNewFoodIngredients;

    private InfoMultiAdapter infoMultiAdapter;

    public final static String FOOD_INFO_KEY = "foodInfoKey";
    public final static String SUPPLIER_NAME_KEY = "supplierName";
    public final static String CATEGORY_NAME_KEY = "categoryName";
    /**
     * 編輯食品的resultCode
     */
    public final static int EDIT_FOOD_RESULT_CODE = 1060;
    /**
     * 是修改還是新增
     * ture:修改
     * false:新增
     */
    public boolean isUpdate = false;

    public static NewFoodIngredientsFragment newInstance(PurchaseFoodBean purchaseFoodBean) {
        NewFoodIngredientsFragment fragment = new NewFoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(FOOD_INFO_KEY, purchaseFoodBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static NewFoodIngredientsFragment newInstance(String supplierName, String categoryName) {
        NewFoodIngredientsFragment fragment = new NewFoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putString(SUPPLIER_NAME_KEY, supplierName);
        bundle.putString(CATEGORY_NAME_KEY, categoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        PermissionX.init(this)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "上傳食材圖片需要文件讀取權限", "確定", "取消"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟文件讀取權限", "確定", "取消"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        //權限通過
                        killMyself();
                    }
                });
        Bundle arguments = getArguments();
        PurchaseFoodBean purchaseFoodBean;

        if (arguments != null) {
            purchaseFoodBean = (PurchaseFoodBean) arguments.getSerializable(FOOD_INFO_KEY);
            if (purchaseFoodBean == null) {
                isUpdate = false;
                initTopBar(topbarNewFoodIngredients, "新增食材");
                purchaseFoodBean = new PurchaseFoodBean();
                //拿到分類集合
                String categoryName = arguments.getString(CATEGORY_NAME_KEY);
                if (TextUtil.isNotEmptyOrNullOrUndefined(categoryName)) {
                    //分類不為空，設置分類信息
                    List<String> categoryNames = new ArrayList<>();
                    categoryNames.add(categoryName);
                    mPresenter.setCategoryNames(categoryNames);
                    purchaseFoodBean.setFoodCategoryName(categoryName);
                }
                //供應商名稱
                purchaseFoodBean.setSupplierName(arguments.getString(SUPPLIER_NAME_KEY));
                mPresenter.setPurchaseFoodBean(purchaseFoodBean);
                initAdapter();
            } else {
                isUpdate = true;
                initTopBar(topbarNewFoodIngredients, "編輯食材");
                //編輯食材需要先去獲取食材詳情
                mPresenter.getIngredientsDetails(purchaseFoodBean.getId());
            }
        }
    }

    @Override
    public void initAdapter() {
        infoMultiAdapter = new InfoMultiAdapter(mContext, mPresenter.getFragmentInfo(mContext));
        rvNewFoodIngredients.addItemDecoration(new DividerItemDecoration(mContext, VERTICAL_LIST));
        infoMultiAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<InfoMultiBean> data = infoMultiAdapter.getData();
            InfoMultiBean infoMultiBean = data.get(position);
            if (infoMultiBean.getItemType() == InfoMultiBean.EDIT_FOOD_ITEM_SELECT) {
                if (infoMultiBean instanceof MultiSelectBean) {
                    MultiSelectBean multiBean = (MultiSelectBean) infoMultiBean;
                    if (infoMultiBean.getFragment() == SupplierListFragment.class) {
                        //選擇供應商
                        startForResult(SupplierListFragment.newInstance(true, multiBean.getShowValue()), multiBean.getRequestCode());
                    } else if (infoMultiBean.getFragment() == CategorySelectFragment.class) {
                        //選擇分類
                        startForResult(CategorySelectFragment.newInstance(mPresenter.getCategoryName()), multiBean.getRequestCode());
                    } else if (infoMultiBean.getFragment() == FoodUnitPageFragment.class) {
                        //食品單位
                        startForResult(FoodUnitPageFragment.newInstance(mPresenter.getBasicUnit(data), mPresenter.getDeputyUnitBeans(), isUpdate, mPresenter.getFoodId()), multiBean.getRequestCode());
                    }
                }
            }
        });
        //圖片點擊事件
        infoMultiAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            SelectPicture.getInstance().showSelectType(this);
        });
        rvNewFoodIngredients.setAdapter(infoMultiAdapter);
    }

    @OnClick({R2.id.btn_save_new_food_ingredients})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_save_new_food_ingredients) {
            //保存
            saveGoodsInfo();
        }
    }

    private void saveGoodsInfo() {
        String msg = mPresenter.verificationData(infoMultiAdapter.getData());
        if (TextUtil.isNotEmptyOrNullOrUndefined(msg)) {
            ToastUtils.show(mContext, msg);
        } else {
            if (isUpdate) {
                mPresenter.updateFood(mPresenter.getFoodInfoByInfoMulti(infoMultiAdapter.getData()));
            } else {
                mPresenter.addFoodInfo(mPresenter.getFoodInfoByInfoMulti(infoMultiAdapter.getData()));
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == SELECT_SUPPLIER_RESULTCODE) {
                //選擇供應商
                SupplierInfoBean supplierInfoBean = (SupplierInfoBean) data.get(SELECT_SUPPLIER_DATA);
                if (supplierInfoBean != null) {
                    mPresenter.setSupplierInfo(supplierInfoBean, infoMultiAdapter.getData());
                }
            } else if (requestCode == SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE && resultCode == RESULT_OK) {
                //基本單位和副單位
                String basicUnitName = data.getString(BASIC_UNIT_KEY);
                List<DeputyUnitBean> deputyUnitBeans = (List<DeputyUnitBean>) data.getSerializable(DEPUTY_UNIT_KEY);
                mPresenter.setPackingInfo(basicUnitName, deputyUnitBeans, infoMultiAdapter.getData());
            } else if (requestCode == SELECT_FOOD_CATEGORY_REQUEST_CODE) {
                //選擇食材類別
                List<OrderCategoryBean.FoodCategoryTrees> sectionCheckItems = (List<OrderCategoryBean.FoodCategoryTrees>) data.get(SELECT_CATEGORY_DATA_KEY);
                if (sectionCheckItems != null) {
                    mPresenter.setCategoryInfo(sectionCheckItems, infoMultiAdapter.getData());
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SelectPicture.CHOOSE_PHOTO && resultCode == RESULT_OK) {
            //從相冊選取完圖片之後
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    File file = SelectPicture.getInstance().uriToFileApiQ(requireContext(), uri);
                    SelectPicture.getInstance().crop(Uri.fromFile(file), this);
                }
            }
        } else if (requestCode == SelectPicture.TAKE_PHOTO && resultCode == RESULT_OK) {
            //拍照
            //拍照完成後需要裁剪
            SelectPicture.getInstance().crop(SelectPicture.getInstance().getmCameraUri(), this);
        } else if (requestCode == REQUEST_CROP && resultCode == RESULT_OK && data != null) {
            final Uri resultUri = UCrop.getOutput(data);
            if (resultUri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, resultUri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            }
        }
    }

    @Override
    public void refreshAdapterByPosition(int position) {
        if (infoMultiAdapter != null) {
            infoMultiAdapter.notifyItemChanged(position);
        }
    }

    @Override
    public void uploadPicSuccess(List<String> picUrl) {
        mPresenter.setPicUrl(infoMultiAdapter.getData(), picUrl);
    }

    @Override
    public void updateFoodInfoSuccess(String supplierName, String categoryName) {
        Bundle bundle = new Bundle();
        bundle.putString(SUPPLIER_NAME_KEY, supplierName);
        bundle.putString(CATEGORY_NAME_KEY, categoryName);
        setFragmentResult(EDIT_FOOD_RESULT_CODE, bundle);
        isLeave = true;
        killMyself();
    }

    /**
     * 用戶是否決定離開這個頁面
     */
    private boolean isLeave = false;

    @Override
    public boolean onBackPressedSupport() {
        if (mPresenter.isUpdate(infoMultiAdapter.getData()) && !isLeave) {
            //用戶修改了數據，提示是否保存
            AppDialog.getInstance().showTipDialog(requireContext(), getString(R.string.str_info_no_save_leave), getString(R.string.str_save), getString(R.string.str_leave), (view, dialog) -> {
                dialog.dismiss();
                saveGoodsInfo();
            }, (view, dialog) -> {
                isLeave = true;
                killMyself();
            });
            return true;
        }
        return super.onBackPressedSupport();
    }
}
