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.RestaurantInfoManager;
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.DeputyUnitBean;
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 List<DeputyUnitBean> deputyUnitBeans;
    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, "食材類別", true, "請選擇食材類別", 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(foodIngredientCategoryIndex).setShowValue(purchaseFoodBean.getFoodCategoryName());
            //基本單位
            infoMultiBeans.get(basicUnitIndex).setShowValue(purchaseFoodBean.getBasicUnitName());
            //包裝描述
            infoMultiBeans.get(packingDescriptionIndex).setShowValue(purchaseFoodBean.getPackingDescription());
            //食品編號
            infoMultiBeans.get(foodNoIndex).setShowValue(purchaseFoodBean.getFoodNo());
            //單價
            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 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) {
        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<SectionCheckItem> sectionCheckItems, List<InfoMultiBean> infoMultiBeans) {
        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(infoMultiBeans.get(supplierIndex).getShowValue())) {
            msg = "請輸入供應商名稱";
        } else if (TextUtil.isEmptyOrNullOrUndefined(infoMultiBeans.get(foodNameIndex).getShowValue())) {
            msg = "請輸入食材名稱";
        } else if (TextUtil.isEmptyOrNullOrUndefined(categoryName)) {
            msg = "請選擇食材類別";
        }
        return msg;
    }

    public PurchaseFoodBean getFoodInfoByInfoMulti(List<InfoMultiBean> infoMultiBeans) {
        if (purchaseFoodBean == null) {
            purchaseFoodBean = new PurchaseFoodBean();
        }
        //食材圖片
        if (TextUtil.isNotEmptyOrNullOrUndefined(picUrl)) {
            purchaseFoodBean.setImages(picUrl);
        }
        //食材所屬供應商
        purchaseFoodBean.setSupplierName(infoMultiBeans.get(supplierIndex).getShowValue());
        //食材名稱
        purchaseFoodBean.setName(infoMultiBeans.get(foodNameIndex).getShowValue());
        //食材類別名稱
        purchaseFoodBean.setFoodCategoryName(categoryName);
        //食材基本單位
        purchaseFoodBean.setBasicUnitName(infoMultiBeans.get(basicUnitIndex).getShowValue());
        //包裝描述
        purchaseFoodBean.setPackingDescription(infoMultiBeans.get(packingDescriptionIndex).getShowValue());
        //食材編號
        purchaseFoodBean.setFoodNo(infoMultiBeans.get(foodNoIndex).getShowValue());
        //單價
        purchaseFoodBean.setUnitPrice(Double.parseDouble(infoMultiBeans.get(foodIngredientPriceIndex).getShowValue()));
        //庫存預警
        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);
        }
        //庫存預警：保質期天數
        String shelfLife = infoMultiBeans.get(shelfLifeIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(shelfLife)) {
            inventoryAlarm.setShelfLife(Integer.parseInt(shelfLife));
        } else {
            inventoryAlarm.setShelfLife(0);
        }
        //庫存預警：保質期預警天數（到期時間 小於等於 預警天數 預警提示用戶）
        String shelfLifeWarning = infoMultiBeans.get(shelfLifeWarningIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(shelfLifeWarning)) {
            inventoryAlarm.setWarningDays(Integer.parseInt(shelfLifeWarning));
        } else {
            inventoryAlarm.setWarningDays(0);
        }
        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;
    }
}
