package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.text.InputFilter;
import android.util.Log;
import android.view.inputmethod.EditorInfo;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
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.bean.SectionCheckItem;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.FoodPackingSpecificationBean;
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.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.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.List;

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 SupplierInfoBean supplierInfoBean;
    private List<FoodPackingSpecificationBean> foodPackingSpecificationBeans;
    private List<SectionCheckItem> sectionCheckItems;
    private String categoryName = "";
    private String picUrl;
    /**
     * 如果是修改食材，則不為空
     */
    private PurchaseFoodBean purchaseFoodBean;
    @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 List<InfoMultiBean> getFragmentInfo() {
        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, SupplierListFragment.newInstance(true)));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材名稱", true, "請輸入名稱"));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "食材類別", false, "請輸入/選擇食材類別", SELECT_FOOD_CATEGORY_REQUEST_CODE, CategorySelectFragment.newInstance()));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "基本單位", false, "請選擇食材單位", SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE, FoodUnitPageFragment.newInstance("",null)));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "包裝說明", false, "請輸入包裝說明"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材編號", false, "請輸入食材編號"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "單價($)", false, "請輸入數字，保留2位小數", "0"));
        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[]{new InputFilter.LengthFilter(5)}, EditorInfo.TYPE_CLASS_NUMBER));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "保質期(天)", false, "請輸入保質期", new InputFilter[]{new InputFilter.LengthFilter(5)}, EditorInfo.TYPE_CLASS_NUMBER));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "保質期預警(天)", false, "請輸入預警天數", new InputFilter[]{new InputFilter.LengthFilter(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, "請輸入備註"));
        if (purchaseFoodBean != null) {
            infoMultiBeans.get(supplierIndex).setShowValue(purchaseFoodBean.getSupplierName());
            infoMultiBeans.get(foodNameIndex).setShowValue(purchaseFoodBean.getName());
            infoMultiBeans.get(packingDescriptionIndex).setShowValue(purchaseFoodBean.getPackingDescription());
            infoMultiBeans.get(foodNoIndex).setShowValue(purchaseFoodBean.getFoodNo());
            infoMultiBeans.get(foodIngredientCategoryIndex).setShowValue(purchaseFoodBean.getFoodCategoryName());
            infoMultiBeans.get(foodIngredientPriceIndex).setShowValue(purchaseFoodBean.getUnitPrice() + "");
//            infoMultiBeans.get(mixInventoryIndex).setShowValue(purchaseFoodListVosBean.get);
            infoMultiBeans.get(remarkIndex).setShowValue(purchaseFoodBean.getRemarks());
            setPicUrl(infoMultiBeans, Collections.singletonList(purchaseFoodBean.getImages()));
        }
        return infoMultiBeans;
    }

    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);
            }
        }
    }


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

    /**
     * 設置包裝信息
     *
     * @param foodPackingSpecificationBeans
     */
    public void setPackingInfo(List<FoodPackingSpecificationBean> foodPackingSpecificationBeans, List<InfoMultiBean> infoMultiBeans) {
        this.foodPackingSpecificationBeans = foodPackingSpecificationBeans;
        if (foodPackingSpecificationBeans != null && foodPackingSpecificationBeans.size() > 1) {
            FoodPackingSpecificationBean foodPackingSpecificationBean = foodPackingSpecificationBeans.get(0);
            infoMultiBeans.get(packingDescriptionIndex).setShowValue(foodPackingSpecificationBean.getQuantityStarts() + "-" + foodPackingSpecificationBean.getQuantityEnd() + "/" + foodPackingSpecificationBean.getTypeName());
            mRootView.refreshAdapterByPosition(packingDescriptionIndex);
        }
    }


    public void setCategoryInfo(List<SectionCheckItem> sectionCheckItems, List<InfoMultiBean> infoMultiBeans) {
        this.sectionCheckItems = sectionCheckItems;
        StringBuilder categoryName = new StringBuilder();
        for (SectionCheckItem sectionCheckItem : sectionCheckItems) {
            categoryName.append(sectionCheckItem.getText())
                    .append("-");
        }
        this.categoryName = sectionCheckItems.get(sectionCheckItems.size() - 1).getText();
        categoryName.deleteCharAt(categoryName.lastIndexOf("-"));
        infoMultiBeans.get(foodIngredientCategoryIndex).setShowValue(categoryName.toString());
        mRootView.refreshAdapterByPosition(foodIngredientCategoryIndex);
    }

    public void uploadPic(String filePath) {
        File file = new File(BitmapUtil.compressImage(filePath));
        Log.e("eee", "文件大小：" + file.length() / 1000 + "/KB");
        List<MultipartBody.Part> multipartBodies = new ArrayList<>();
        multipartBodies.add(MultipartBody.Part.createFormData("files", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)));
        mModel.upLoadPic(multipartBodies)
                .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);
                            }
                        }
                    }
                });
    }

    /**
     * 添加食品
     *
     * @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("保存中..."))
                .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("保存成功");
                            mRootView.saveFoodInfoSuccess();
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage("保存失敗");
                        }
                    }
                });
    }


    /**
     * 修改食品
     *
     * @param purchaseFoodBean
     * @param position
     */
    public void updateFood(PurchaseFoodBean purchaseFoodBean, int position) {
        mModel.updateFood(RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(purchaseFoodBean)))
                .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()) {
//                            mRootView.onDeleteFoodSuccess(position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage("刪除失敗，請稍候重試");
                        }
                    }
                });
    }
    public String verificationData(List<InfoMultiBean> infoMultiBeans) {
        String msg = null;
//        if (TextUtil.isEmptyOrNullOrUndefined(picUrl)){
//            msg = "請上傳圖片";
//        } else
        if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(supplierIndex).getShowValue())) {
            msg = "請輸入供應商名稱";
        } else if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(foodNameIndex).getShowValue())) {
            msg = "請輸入食材名稱";
        } else if (foodPackingSpecificationBeans == null) {
            msg = "請選擇包裝規格";
        } else if (TextUtil.isEmptyOrNullOrUndefined(categoryName)) {
            msg = "請選擇食材類別";
        }
        return msg;
    }

    public PurchaseFoodBean getFoodInfoByInfoMulti(List<InfoMultiBean> infoMultiBeans) {
        PurchaseFoodBean foodInfoBean = new PurchaseFoodBean();
        foodInfoBean.setBrandId(ResturantInfoManager.newInstance().getBrandId());
        foodInfoBean.setRestaurantId(ResturantInfoManager.newInstance().getRestaurantId());
        foodInfoBean.setFoodNo(infoMultiBeans.get(foodNoIndex).getShowValue());
        foodInfoBean.setName(infoMultiBeans.get(foodNameIndex).getShowValue());
        if (TextUtil.isNotEmptyOrNullOrUndefined(picUrl)) {
            foodInfoBean.setImages(picUrl);
        }
        foodInfoBean.setSupplierName(infoMultiBeans.get(supplierIndex).getShowValue());
        foodInfoBean.setFoodCategoryName(categoryName);
        foodInfoBean.setUnitPrice(Double.parseDouble(infoMultiBeans.get(foodIngredientPriceIndex).getShowValue()));
//        foodInfoBean.setReviews("是否需要審核");
        foodInfoBean.setRemarks(infoMultiBeans.get(remarkIndex).getShowValue());
        PurchaseFoodBean.InventoryAlarm inventoryAlarm = new PurchaseFoodBean.InventoryAlarm();
//        inventoryAlarm.setFoodUnitId();
        if (TextUtil.isNotEmptyOrNullOrUndefined(infoMultiBeans.get(mixInventoryIndex).getShowValue())) {
//            inventoryAlarm.setMinimumInventory(Integer.parseInt(infoMultiBeans.get(mixInventoryIndex).getShowValue()));
        }
        foodInfoBean.setInventoryAlarm(inventoryAlarm);
//        foodInfoBean.setFoodPackingSpecifications(foodPackingSpecificationBeans);
        return foodInfoBean;
    }


}
