package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.view.inputmethod.EditorInfo;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.DecimalDigitsInputFilter;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.view.BitmapUtil;
import com.gingersoft.gsa.cloud.ui.adapter.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.MultiInputBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.MultiSelectBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.UploadPicMultiBean;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
import com.gingersoft.supply_chain.R;
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.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.NewFoodIngredientsContract;
import com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodUnitPageFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment;
import com.gingersoft.supply_chain.mvp.utils.ResultUtils;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

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.PackageSpecificationFragment.SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment.SELECT_SUPPLIER_RESULTCODE;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/24/2020 16:13
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class NewFoodIngredientsPresenter extends BasePresenter<NewFoodIngredientsContract.Model, NewFoodIngredientsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    public int picIndex = 2;
    public int supplierIndex = 5;
    public int foodNameIndex = 6;
    public int foodIngredientCategoryIndex = 7;
    /**
     * 基本單位下標
     */
    public int basicUnitIndex = 8;
    /**
     * 包裝說明下標
     */
    public int packingDescriptionIndex = 9;
    /**
     * 食材編號下標
     */
    public int foodNoIndex = 10;
    /**
     * 食材sn碼下標
     */
    public int foodSnIndex = 11;
    /**
     * 食材單價下標
     */
    public int foodIngredientPriceIndex = 12;
    /**
     * 是否審核 下標
     */
    public int isAuditIndex = 15;
    public int mixInventoryIndex = 16;//最低庫存
    public int shelfLifeIndex = 17;//保質期
    public int shelfLifeWarningIndex = 18;//保質期預警
    public int remarkIndex = 21;//備註
    /**
     * 副單位集合
     */
    private List<DeputyUnitBean> deputyUnitBeans;
    //    private String categoryName = "";
    private String picUrl;
    /**
     * 如果是修改食材，則不為空
     */
    private PurchaseFoodBean purchaseFoodBean;
    /**
     * 分類名：一級，二級，三級
     */
    private List<String> categoryNames;

    @Inject
    public NewFoodIngredientsPresenter(NewFoodIngredientsContract.Model model, NewFoodIngredientsContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void setPurchaseFoodBean(PurchaseFoodBean purchaseFoodBean) {
        this.purchaseFoodBean = purchaseFoodBean;
    }

    public void setCategoryNames(List<String> categoryNames) {
        this.categoryNames = categoryNames;
    }

    public String getCategoryName() {
        if (categoryNames != null && categoryNames.size() > 0) {
            return categoryNames.get(categoryNames.size() - 1);
        }
        return "";
    }

    /**
     * 獲取食材詳情
     */
    public void getIngredientsDetails(int ingredientId) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("id", ingredientId);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        mModel.getFoodIngredientsDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (ResultUtils.isSuccess(baseResult, AppConstant.NULL_INFO_ERROR, mRootView)) {
                            PurchaseFoodBean purchaseFoodBean = GsonUtils.GsonToBean(baseResult.getData(), PurchaseFoodBean.class);
                            if (purchaseFoodBean != null) {
                                purchaseFoodBean.setId(ingredientId);
                                PurchaseFoodBean.InventoryAlarm inventoryAlarm = new PurchaseFoodBean.InventoryAlarm();
                                inventoryAlarm.setId(purchaseFoodBean.getInventoryWarningId());
                                inventoryAlarm.setWarningDays(purchaseFoodBean.getWarningDays());
                                inventoryAlarm.setShelfLife(purchaseFoodBean.getShelfLife());
                                inventoryAlarm.setReviews(purchaseFoodBean.isReviews() ? 1 : 0);
                                inventoryAlarm.setMinimumInventory(purchaseFoodBean.getMinimumInventory());
                                purchaseFoodBean.setInventoryAlarm(inventoryAlarm);
                                setPurchaseFoodBean(purchaseFoodBean);
                                mRootView.initAdapter();
                            } else {
                                mRootView.showMessage(AppConstant.NULL_INFO_ERROR);
                            }
                        }
                    }
                });

    }

    public List<InfoMultiBean> getFragmentInfo(Context context) {
        List<InfoMultiBean> infoMultiBeans = new ArrayList<>();
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "商品圖片"));
        infoMultiBeans.add(new UploadPicMultiBean(InfoMultiBean.EDIT_FOOD_ITEM_UPLOAD_PIC, "圖片上傳", R.drawable.png_upload_pic));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "基本信息"));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "所屬供應商", true, "請輸入/選擇供應商", SELECT_SUPPLIER_RESULTCODE, true, SupplierListFragment.class));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材名稱", true, "請輸入名稱", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 200), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(context)}, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "食材類別", true, "請選擇食材類別", SELECT_FOOD_CATEGORY_REQUEST_CODE, CategorySelectFragment.class));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "基本單位", true, "請選擇食材單位", SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE, FoodUnitPageFragment.class));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "包裝說明", false, "請輸入包裝說明", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 10), InputFilterUtils.getTypeFilter(context, InputFilterUtils.chAndEnAndNumAndSlash)}));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材編號", false, "請輸入食材編號", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 32), InputFilterUtils.getEnAndNumInputFilter(context)}));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_MULTIPLE_BOOLEAN, "是否有SN碼", false, false));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "單價($)", false, "請輸入單價，保留2位小數", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 9), new DecimalDigitsInputFilter(context, 2)}, InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "庫存預警"));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_MULTIPLE_BOOLEAN, "是否審核", false, ""));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "最低庫存", false, "請輸入最低庫存", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 5)}, EditorInfo.TYPE_CLASS_NUMBER));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "保質期(天)", false, "請輸入保質期", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 5)}, EditorInfo.TYPE_CLASS_NUMBER));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "保質期預警(天)", false, "請輸入預警天數", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 5)}, EditorInfo.TYPE_CLASS_NUMBER));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "備註"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_MULTIPLE_INPUT_REMARK, "", false, "請輸入備註", new InputFilter[]{InputFilterUtils.getLengthFilter(context, RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnNumPtWrapInputFilter(context)}).setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE));
        if (purchaseFoodBean != null) {
            //供應商名稱
            String supplierName = purchaseFoodBean.getSupplierName();
            infoMultiBeans.get(supplierIndex).setShowValue(supplierName);
//            if (TextUtil.isNotEmptyOrNullOrUndefined(supplierName)) {
            InfoMultiBean inputMulti = infoMultiBeans.get(supplierIndex);
            if (inputMulti instanceof MultiSelectBean) {
                ((MultiSelectBean) inputMulti).setEdit(false);
            }
//            }
            //食品名稱
            infoMultiBeans.get(foodNameIndex).setShowValue(purchaseFoodBean.getName());
            //食品分類
            categoryNames = new ArrayList<>();
            categoryNames.add(purchaseFoodBean.getFoodCategoryName());
            infoMultiBeans.get(foodIngredientCategoryIndex).setShowValue(purchaseFoodBean.getFoodCategoryName());
            //基本單位
            infoMultiBeans.get(basicUnitIndex).setShowValue(purchaseFoodBean.getBasicUnitName());
            //包裝描述
            infoMultiBeans.get(packingDescriptionIndex).setShowValue(purchaseFoodBean.getPackingDescription());
            //食品編號
            if (TextUtil.isNotEmptyOrNullOrUndefined(purchaseFoodBean.getFoodNo())) {
                MultiInputBean foodNoInputBean = (MultiInputBean) infoMultiBeans.get(foodNoIndex);
                foodNoInputBean.setEdit(false);
                foodNoInputBean.setShowValue(purchaseFoodBean.getFoodNo());
            }
            //sn食材，新增食材，是否是sn為-1，如果不是-1，則不是新增。就不能修改
            if (purchaseFoodBean.getFoodMarkSn() != -1) {
                infoMultiBeans.set(foodSnIndex, new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "是否有SN碼", false, purchaseFoodBean.getFoodMarkSn() == PurchaseFoodBean.HAS_SN ? "是" : "否").setEdit(false));
            } else {
                //默認不是SN食材
                purchaseFoodBean.setFoodMarkSn(0);
            }
//            infoMultiBeans.get(foodSnIndex).setChecked(purchaseFoodBean.getFoodMarkSn() == PurchaseFoodBean.HAS_SN);
            //單價
            if (purchaseFoodBean.getUnitPrice() != null) {
                infoMultiBeans.get(foodIngredientPriceIndex).setShowValue(purchaseFoodBean.getUnitPrice() + "");
            }
            //預警
            PurchaseFoodBean.InventoryAlarm inventoryAlarm = purchaseFoodBean.getInventoryAlarm();
            if (inventoryAlarm != null) {
                infoMultiBeans.get(isAuditIndex).setChecked(inventoryAlarm.getReviews() == 1);
                infoMultiBeans.get(mixInventoryIndex).setShowValue(inventoryAlarm.getMinimumInventory() + "");
                infoMultiBeans.get(shelfLifeIndex).setShowValue(inventoryAlarm.getShelfLife() + "");
                infoMultiBeans.get(shelfLifeWarningIndex).setShowValue(inventoryAlarm.getWarningDays() + "");
            }
            //備註
            infoMultiBeans.get(remarkIndex).setShowValue(purchaseFoodBean.getRemarks());
            //副單位
            deputyUnitBeans = purchaseFoodBean.getFoodUnits();
            //食材圖片
            setPicUrl(infoMultiBeans, Collections.singletonList(purchaseFoodBean.getImages()));
        }
        return infoMultiBeans;
    }

    public String getBasicUnit(List<InfoMultiBean> infoMultiBeans) {
        return infoMultiBeans.get(basicUnitIndex).getShowValue();
    }

    public Integer getFoodId() {
        if (purchaseFoodBean != null) {
            return purchaseFoodBean.getId();
        }
        return null;
    }

    public void setPicUrl(List<InfoMultiBean> data, List<String> picUrls) {
        InfoMultiBean infoMultiBean = data.get(picIndex);
        if (picUrls != null && picUrls.size() > 0 && TextUtil.isNotEmptyOrNullOrUndefined(picUrls.get(0))) {
            if (infoMultiBean instanceof UploadPicMultiBean) {
                UploadPicMultiBean uploadPicMultiBean = (UploadPicMultiBean) infoMultiBean;
                uploadPicMultiBean.setPicUrl(picUrls);
                mRootView.refreshAdapterByPosition(picIndex);
            }
        }
    }


    /**
     * 設置供應商信息R
     *
     * @param supplierInfoBean
     * @param infoMultiBeans
     */
    public void setSupplierInfo(SupplierInfoBean supplierInfoBean, List<InfoMultiBean> infoMultiBeans) {
        infoMultiBeans.get(supplierIndex).setShowValue(supplierInfoBean.getSupplierName());
        mRootView.refreshAdapterByPosition(supplierIndex);
    }

    /**
     * 設置單位
     */
    public void setPackingInfo(String basicUnitName, List<DeputyUnitBean> deputyUnitBeans, List<InfoMultiBean> infoMultiBeans) {
        infoMultiBeans.get(basicUnitIndex).setShowValue(basicUnitName);
        if (deputyUnitBeans != null) {
            for (DeputyUnitBean deputyUnitBean : deputyUnitBeans) {
                deputyUnitBean.setRestaurantId(AppConstant.getRestaurantId());
                deputyUnitBean.setBrandId(AppConstant.getBrandId());
            }
        }
        this.deputyUnitBeans = deputyUnitBeans;
        mRootView.refreshAdapterByPosition(basicUnitIndex);
    }

    public void setCategoryInfo(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, List<InfoMultiBean> infoMultiBeans) {
        if (CollectionUtils.isNullOrEmpty(foodCategoryTrees)) {
            return;
        }
        StringBuilder categoryName = new StringBuilder();
        if (categoryNames == null) {
            categoryNames = new ArrayList<>();
        }
        categoryNames.clear();

        for (OrderCategoryBean.FoodCategoryTrees categoryTrees : foodCategoryTrees) {
            categoryNames.add(categoryTrees.getName());
            categoryName.append(categoryTrees.getName())
                    .append(PurchaseFoodBean.CATEGORY_DIVIDER);
        }
        if (purchaseFoodBean != null && foodCategoryTrees.size() > 0) {
            //食材信息不為空，設置分類id為最後一個分類的id
            //例如：選擇了一個三級分類，下標0為父類，1為子類，2位當前分類
            purchaseFoodBean.setFoodCategoryId(foodCategoryTrees.get(foodCategoryTrees.size() - 1).getId());
        }
        categoryName.deleteCharAt(categoryName.lastIndexOf(PurchaseFoodBean.CATEGORY_DIVIDER));
        infoMultiBeans.get(foodIngredientCategoryIndex).setShowValue(categoryName.toString());
        mRootView.refreshAdapterByPosition(foodIngredientCategoryIndex);
    }

    /**
     * 上傳圖片
     *
     * @param filePath 圖片路徑
     */
    public void uploadPic(String filePath) {
        File file = new File(BitmapUtil.compressImage(filePath));
        List<MultipartBody.Part> multipartBodies = new ArrayList<>();
        multipartBodies.add(MultipartBody.Part.createFormData("files", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)));
        Map<String, Object> map = new HashMap<>(1);
        map.put("type", PurchaseConstant.UPLOAD_PIC_TYPE_FOOD);
        mModel.upLoadPic(multipartBodies, map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("圖片上傳中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess() && baseResult.getData() != null) {
                            List<String> imgUrl = JsonUtils.parseArray(baseResult.getData(), String.class);
                            if (imgUrl != null && imgUrl.size() > 0) {
                                picUrl = imgUrl.get(0);
                                mRootView.uploadPicSuccess(imgUrl);
                            }
                        }
                        boolean delete = file.delete();
                    }
                });
    }

    /**
     * 添加食品
     *
     * @param purchaseFoodBean
     */
    public void addFoodInfo(PurchaseFoodBean purchaseFoodBean) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseFoodBean));
        mModel.addFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.SAVE_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            mRootView.showMessage(AppConstant.SAVE_SUCCESS);
                            mRootView.updateFoodInfoSuccess(purchaseFoodBean.getSupplierName(), purchaseFoodBean.getFoodCategoryName());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.SAVE_FAIL);
                        }
                    }
                });
    }

    /**
     * 修改食品
     *
     * @param purchaseFoodBean
     */
    public void updateFood(PurchaseFoodBean purchaseFoodBean) {
        //後台不要，不然修改供應商不成功
        int supplierId = purchaseFoodBean.getSupplierId();
        purchaseFoodBean.setSupplierId(null);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseFoodBean));
        mModel.updateFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.UPDATE_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            mRootView.showMessage(AppConstant.UPDATE_SUCCESS);
                            mRootView.updateFoodInfoSuccess(purchaseFoodBean.getSupplierName(), purchaseFoodBean.getFoodCategoryName());
                            purchaseFoodBean.setSupplierId(supplierId);
                            SupplyShoppingCart.getInstance().replaceFood(purchaseFoodBean);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.UPDATE_FAIL);
                        }
                    }
                });
    }

    public String verificationData(List<InfoMultiBean> infoMultiBeans) {
        String msg = null;
        if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(supplierIndex).getShowValue())) {
            msg = "請輸入供應商名稱";
        } else if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(foodNameIndex).getShowValue())) {
            msg = "請輸入食材名稱";
        } else if (TextUtil.isEmptyOrNullOrUndefined(getCategoryName())) {
            msg = "請選擇食材類別";
        } else if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(basicUnitIndex).getShowValue())) {
            msg = "請選擇基本單位";
        }
        return msg;
    }

    public List<DeputyUnitBean> getDeputyUnitBeans() {
        return deputyUnitBeans;
    }

    /**
     * 獲取商品信息
     *
     * @param infoMultiBeans 商品的各項數據
     * @return 商品類
     */
    public PurchaseFoodBean getFoodInfoByInfoMulti(List<InfoMultiBean> infoMultiBeans) {
         if (purchaseFoodBean == null) {
            purchaseFoodBean = new PurchaseFoodBean();
        }
        //這裡拷貝一個類出來，如果本次修改食材沒有成功，也不會影響原有數據
        PurchaseFoodBean purchaseFoodBean = (PurchaseFoodBean) PurchaseFoodBean.copy(this.purchaseFoodBean);
        //食材圖片
        if (TextUtil.isNotEmptyOrNullOrUndefined(picUrl)) {
            purchaseFoodBean.setImages(picUrl);
        }
        //食材所屬供應商
        purchaseFoodBean.setSupplierName(infoMultiBeans.get(supplierIndex).getShowValue());
        //食材名稱
        purchaseFoodBean.setName(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(foodNameIndex).getShowValue()));
        //食材類別名稱
        purchaseFoodBean.setFoodCategoryName(getCategoryName());
        //食材基本單位
        purchaseFoodBean.setBasicUnitName(infoMultiBeans.get(basicUnitIndex).getShowValue());
        //包裝描述
        purchaseFoodBean.setPackingDescription(infoMultiBeans.get(packingDescriptionIndex).getShowValue());
        //食材編號
        String foodNo = infoMultiBeans.get(foodNoIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodNo)) {
            purchaseFoodBean.setFoodNo(infoMultiBeans.get(foodNoIndex).getShowValue());
        } else {
            purchaseFoodBean.setFoodNo(null);
        }
        //是否有sn碼
        purchaseFoodBean.setFoodMarkSn(infoMultiBeans.get(foodSnIndex).isChecked() ? PurchaseFoodBean.HAS_SN : PurchaseFoodBean.NOT_HAS_SN);
        //單價
        String unitPriceStr = infoMultiBeans.get(foodIngredientPriceIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(unitPriceStr)) {
            purchaseFoodBean.setUnitPrice(Double.parseDouble(unitPriceStr));
        } else {
            purchaseFoodBean.setUnitPrice(0d);
        }
        //庫存預警
        //是否修改了庫存預警，如果沒修過，就不傳遞給後台
        boolean isUpdateAlarm = false;
        PurchaseFoodBean.InventoryAlarm inventoryAlarm = new PurchaseFoodBean.InventoryAlarm();
        //庫存預警：是否審核
        inventoryAlarm.setReviews(infoMultiBeans.get(isAuditIndex).isChecked() ? 1 : 0);

        //庫存預警：最低庫存
        String mixInventory = infoMultiBeans.get(mixInventoryIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(mixInventory)) {
            inventoryAlarm.setMinimumInventory(Integer.parseInt(mixInventory));
        } else {
            inventoryAlarm.setMinimumInventory(0);
            mixInventory = "";
        }
        //庫存預警：保質期天數
        String shelfLife = infoMultiBeans.get(shelfLifeIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(shelfLife)) {
            inventoryAlarm.setShelfLife(Integer.parseInt(shelfLife));
        } else {
            inventoryAlarm.setShelfLife(0);
            shelfLife = "";
        }
        //庫存預警：保質期預警天數（到期時間 小於等於 預警天數 預警提示用戶）
        String shelfLifeWarning = infoMultiBeans.get(shelfLifeWarningIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(shelfLifeWarning)) {
            inventoryAlarm.setWarningDays(Integer.parseInt(shelfLifeWarning));
        } else {
            shelfLifeWarning = "";
            inventoryAlarm.setWarningDays(0);
        }
        //對庫存預警四個字段進行驗證，驗證是否修改
        if (purchaseFoodBean.getInventoryAlarm() != null) {
            if (inventoryAlarm.getReviews() != purchaseFoodBean.getInventoryAlarm().getReviews()) {
                isUpdateAlarm = true;
            }
            if (!isUpdateAlarm && !mixInventory.equals(purchaseFoodBean.getInventoryAlarm().getMinimumInventory() + "")) {
                isUpdateAlarm = true;
            }
            if (!isUpdateAlarm && !shelfLife.equals(purchaseFoodBean.getInventoryAlarm().getShelfLife() + "")) {
                isUpdateAlarm = true;
            }
            if (!isUpdateAlarm && !shelfLifeWarning.equals(purchaseFoodBean.getInventoryAlarm().getWarningDays() + "")) {
                isUpdateAlarm = true;
            }
            if (isUpdateAlarm) {
                //修改了庫存預警，並且之前的預警不為空，把id設置上
                inventoryAlarm.setId(purchaseFoodBean.getInventoryAlarm().getId());
                purchaseFoodBean.setInventoryAlarm(inventoryAlarm);
            } else {
                //沒修改庫存預警，就不傳給後台
                purchaseFoodBean.setInventoryAlarm(null);
            }
        } else {
            purchaseFoodBean.setInventoryAlarm(inventoryAlarm);
        }
        //備註
        purchaseFoodBean.setRemarks(infoMultiBeans.get(remarkIndex).getShowValue());
        //副單位
        if (deputyUnitBeans != null && deputyUnitBeans.size() > 0) {
            purchaseFoodBean.setFoodUnits(deputyUnitBeans);
        }
        //品牌id
        purchaseFoodBean.setBrandId(AppConstant.getBrandId());
        //餐廳id
        purchaseFoodBean.setRestaurantId(AppConstant.getRestaurantId());
        return purchaseFoodBean;
    }


    public boolean isUpdate(List<InfoMultiBean> infoMultiBeans) {
        PurchaseFoodBean foodInfoByInfoMulti = getFoodInfoByInfoMulti(infoMultiBeans);
        purchaseFoodBean.initPartValue();
        return !foodInfoByInfoMulti.equals(purchaseFoodBean);
    }

}
