package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.util.Log;
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.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.bean.MultiInputBean;
import com.gingersoft.gsa.cloud.ui.bean.MultiSelectBean;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
import com.gingersoft.gsa.cloud.ui.bean.UploadPicMultiBean;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.FoodPackingSpecificationBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodListVosBean;
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.PackageSpecificationFragment;
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 packageSpecificationIndex = 7;
    public int foodNoIndex = 8;
    public int foodIngredientCategoryIndex = 9;
    public int foodIngredientPriceIndex = 10;
    public int inventoryAlarmUnitIndex = 13;
    public int mixInventoryIndex = 14;
    public int remarkIndex = 17;

    private SupplierInfoBean supplierInfoBean;
    private List<FoodPackingSpecificationBean> foodPackingSpecificationBeans;
    private List<SectionCheckItem> sectionCheckItems;
    private String categoryName = "";
    private String picUrl;

    @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 List<InfoMultiBean> getFragmentInfo(PurchaseFoodListVosBean purchaseFoodListVosBean) {
        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, "包裝規格", true, "請輸入/選擇包裝規格", SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE, PackageSpecificationFragment.newInstance()));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "食材編號", false, "請輸入食材編號"));
        infoMultiBeans.add(new MultiSelectBean(InfoMultiBean.EDIT_FOOD_ITEM_SELECT, "食材類別", true, "請輸入/選擇食材類別", SELECT_FOOD_CATEGORY_REQUEST_CODE, CategorySelectFragment.newInstance()));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "單價(HKD)", false, "請輸入數字，保留2位小數", "0"));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "庫存預警"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "單位", false, "請輸入單位"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "最低庫存", false, "請輸入最低庫存"));
        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 (purchaseFoodListVosBean != null) {
            infoMultiBeans.get(supplierIndex).setShowValue(purchaseFoodListVosBean.getSupplierName());
            infoMultiBeans.get(foodNameIndex).setShowValue(purchaseFoodListVosBean.getName());
            infoMultiBeans.get(packageSpecificationIndex).setShowValue(purchaseFoodListVosBean.getUnitContent());
            infoMultiBeans.get(foodNoIndex).setShowValue(purchaseFoodListVosBean.getFoodNo());
            infoMultiBeans.get(foodIngredientCategoryIndex).setShowValue("選擇分類");
            infoMultiBeans.get(foodIngredientPriceIndex).setShowValue(purchaseFoodListVosBean.getUnitPrice() + "");
            infoMultiBeans.get(inventoryAlarmUnitIndex).setShowValue("收貨單位");
            infoMultiBeans.get(mixInventoryIndex).setShowValue("1");
            infoMultiBeans.get(remarkIndex).setShowValue("備註");
            setPicUrl(infoMultiBeans, Collections.singletonList(purchaseFoodListVosBean.getImages()));
        }
        return infoMultiBeans;
    }

    public void setPicUrl(List<InfoMultiBean> data, List<String> picUrls) {
        InfoMultiBean infoMultiBean = data.get(picIndex);
        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(packageSpecificationIndex).setShowValue(foodPackingSpecificationBean.getQuantityStarts() + "-" + foodPackingSpecificationBean.getQuantityEnd() + "/" + foodPackingSpecificationBean.getTypeName());
            mRootView.refreshAdapterByPosition(packageSpecificationIndex);
        }
    }


    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 purchaseFoodListVosBean
     */
    public void addFoodInfo(PurchaseFoodListVosBean purchaseFoodListVosBean) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseFoodListVosBean));
        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("保存失敗");
                        }
                    }
                });
    }

    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 PurchaseFoodListVosBean getFoodInfoByInfoMulti(List<InfoMultiBean> infoMultiBeans) {
        PurchaseFoodListVosBean foodInfoBean = new PurchaseFoodListVosBean();
        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());
        PurchaseFoodListVosBean.InventoryAlarm inventoryAlarm = new PurchaseFoodListVosBean.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;
    }
}
