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.core.restaurant.RestaurantInfoManager;
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.gsa.cloud.ui.bean.SectionCheckItem;
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.Constant;
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;
    /**
     * 食材單價下標
     */
    public int foodIngredientPriceIndex = 11;
    /**
     * 是否審核 下標
     */
    public int isAuditIndex = 14;
    public int mixInventoryIndex = 15;//最低庫存
    public int shelfLifeIndex = 16;//保質期
    public int shelfLifeWarningIndex = 17;//保質期預警
    public int remarkIndex = 20;//備註
    /**
     * 副單位集合
     */
    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);
        Constant.addBrandId(map);
        Constant.addRestaurantId(map);
        mModel.getFoodIngredientsDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.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, Constant.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(Constant.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, new InputFilter[]{InputFilterUtils.getLengthFilter(context, 16), InputFilterUtils.getChAndEnAndNumInputFilter(context)}, SupplierListFragment.class));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材名稱", true, "請輸入名稱", new InputFilter[]{InputFilterUtils.getLengthFilter(context, 100), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(context)}));
        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, 11), InputFilterUtils.getEnAndNumInputFilter(context)}));
        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.getChAndEnAndNumAndPtInputFilter(context)}));
        if (purchaseFoodBean != null) {
            //供應商名稱
            infoMultiBeans.get(supplierIndex).setShowValue(purchaseFoodBean.getSupplierName());
            //食品名稱
            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());
            }
            //單價
            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(RestaurantInfoManager.newInstance().getRestaurantId());
                deputyUnitBean.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
            }
        }
        this.deputyUnitBeans = deputyUnitBeans;
        mRootView.refreshAdapterByPosition(basicUnitIndex);
    }

    public void setCategoryInfo(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, List<InfoMultiBean> infoMultiBeans) {
        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) {
            //食材信息不為空，設置分類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", Constant.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(Constant.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(Constant.SAVE_SUCCESS);
                            mRootView.updateFoodInfoSuccess(purchaseFoodBean.getSupplierName(), purchaseFoodBean.getFoodCategoryName());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.SAVE_FAIL);
                        }
                    }
                });
    }

    /**
     * 修改食品
     *
     * @param purchaseFoodBean
     */
    public void updateFood(PurchaseFoodBean purchaseFoodBean) {
        //後台不要，不然修改供應商不成功
        purchaseFoodBean.setSupplierId(null);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseFoodBean));
        mModel.updateFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.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(Constant.UPDATE_SUCCESS);
                            mRootView.updateFoodInfoSuccess(purchaseFoodBean.getSupplierName(), purchaseFoodBean.getFoodCategoryName());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.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;
    }

    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(infoMultiBeans.get(foodNameIndex).getShowValue().trim());
        //食材類別名稱
        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);
        }
        //單價
        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(RestaurantInfoManager.newInstance().getBrandId());
        //餐廳id
        purchaseFoodBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
        return purchaseFoodBean;
    }
}
