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.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.MatchUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.adapter.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.MultiCheckInputBean;
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.multi.InfoMultiAdapter;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
import com.gingersoft.supply_chain.R;
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.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.NewSupplierContract;
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.EnAndNumInputFilter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

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

import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Email;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Kakao_Talk;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Line;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.SMS;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.WeChat;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Whatsapp;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/19/2020 18:33
 * <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 NewSupplierPresenter extends BasePresenter<NewSupplierContract.Model, NewSupplierContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    public final int supplierNoIndex = 2;
    public final int supplierNameIndex = 3;
    public final int contactsIndex = 4;
    public final int addressIndex = 5;
    public final int telephoneIndex = 6;
    public final int lowPurchaseAmount = 7;
    //運費
    public final int shippingIndex = 8;

    public final int emailIndex = 11;
    public final int smsIndex = 16;
    public final int remarkIndex = 19;

    public final int WhatsAppIndex = 12;
    public final int weChatIndex = 13;
    public final int lineIndex = 14;
    public final int kakaoIndex = 15;

    private InfoMultiAdapter infoMultiAdapter;
    private SupplierInfoBean supplierBean;
    /**
     * 記錄供應商名稱
     * 如果是修改供應商，修改了名稱之後，需要更新名稱，
     * 如果沒修改名稱，則不傳給後台
     */
    private String supplierName = "";

    private List<MultiCheckInputBean> contactInfo = new ArrayList<>();

    private List<SupplierInfoBean.SupplierContacts> supplierContacts;

    @Inject
    public NewSupplierPresenter(NewSupplierContract.Model model, NewSupplierContract.View rootView) {
        super(model, rootView);
    }

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

    public InfoMultiAdapter initAdapter(Context mContext, SupplierInfoBean supplierBean) {
        this.supplierBean = supplierBean;
//        InputFilter chAndEnAndNumInputFilter = InputFilterUtils.getChAndEnAndNumInputFilter(mContext);
        List<InfoMultiBean> infoMultiBeans = new ArrayList<>();
        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, "請輸入編號", new InputFilter[]{new InputFilter.LengthFilter(11), new EnAndNumInputFilter()}));
        MultiInputBean multiInputSupplierName = new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "名稱", true, "請輸入名稱", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 100), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(mContext)}, mSupplierNameChangeListener);
        multiInputSupplierName.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        infoMultiBeans.add(multiInputSupplierName);
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "聯繫人", true, "請輸入聯繫人", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "詳細地址", true, "請輸入詳細地址", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 150), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(mContext)}, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "聯繫人電話", true, "請輸入聯繫人電話", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 11)}, EditorInfo.TYPE_CLASS_PHONE));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "最低採購金額", false, "請輸入最低金額", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 9)}, EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_FLAG_DECIMAL));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "運費", false, "請輸入運費", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 9)}, EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_FLAG_DECIMAL));

        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "接收方式"));

//        InfoMultiBean receivingMode = new InfoMultiBean(InfoMultiBean.ITEM_TYPE_SHOW_LIST, "接收軟件", false, "", "選擇");
//        List<InfoMultiBean> childInfoMulti = new ArrayList<>();
//        childInfoMulti.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "WhatsApp", false, "請輸入WhatsApp"));
//        childInfoMulti.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "WeChat", false, "請輸入WeChat"));
//        childInfoMulti.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "Line", false, "請輸入Line"));
//        childInfoMulti.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "Kakao Talk", false, "請輸入Kakao Talk"));
//        receivingMode.setInfoMultiBeans(childInfoMulti);
//        infoMultiBeans.add(receivingMode);
        MultiCheckInputBean emailInputBean = new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "Email", false, "請輸入Email", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 40)}, R.drawable.ic_email, false);
        emailInputBean.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        contactInfo.add(emailInputBean);
        contactInfo.add(new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "WhatsApp", false, "請輸入WhatsApp", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, R.drawable.ic_whatsapp, false).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        contactInfo.add(new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "WeChat", false, "請輸入WeChat", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, R.drawable.ic_wechat, false));
        contactInfo.add(new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "Line", false, "請輸入Line", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, R.drawable.ic_line, false));
        contactInfo.add(new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "Kakao Talk", false, "請輸入Kakao Talk", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, R.drawable.ic_talk, false));
        contactInfo.add(new MultiCheckInputBean(InfoMultiBean.ITEM_MULTIPLE_CHECKBOX, "SMS", false, "請輸入SMS", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)}, R.drawable.ic_sms, false));
        infoMultiBeans.addAll(contactInfo);
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "備註").setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE));

        MultiInputBean remarkInputBean = new MultiInputBean(InfoMultiBean.ITEM_MULTIPLE_INPUT_REMARK, null, false, "請輸入備註", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnNumPtWrapInputFilter(mContext)}).setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
        remarkInputBean.setMaxLength(RemarkProvider.REMARK_TEXT_LENGTH);

        infoMultiBeans.add(remarkInputBean);
        if (supplierBean != null) {
            supplierName = supplierBean.getSupplierName();
            infoMultiBeans.get(supplierNoIndex).setShowValue(supplierBean.getSupplierNo());
            ((MultiInputBean) infoMultiBeans.get(supplierNoIndex)).setEdit(false);
            infoMultiBeans.get(supplierNameIndex).setShowValue(supplierBean.getSupplierName());
            infoMultiBeans.get(contactsIndex).setShowValue(supplierBean.getContacts());
            infoMultiBeans.get(telephoneIndex).setShowValue(supplierBean.getContactInformation());
            infoMultiBeans.get(addressIndex).setShowValue(supplierBean.getAddress());
            infoMultiBeans.get(remarkIndex).setShowValue(supplierBean.getRemarks());
            infoMultiBeans.get(lowPurchaseAmount).setShowValue(supplierBean.getMinimumAmount() + "");
            infoMultiBeans.get(shippingIndex).setShowValue(supplierBean.getShipping() + "");
        }
        infoMultiAdapter = new InfoMultiAdapter(mContext, infoMultiBeans);
        infoMultiAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.cb_multi_check) {
                // 聯繫方式的選中
                //先找到之前的默認聯繫方式
                List<InfoMultiBean> data = infoMultiAdapter.getData();
                int lastDefault = emailIndex;
                for (int i = emailIndex; i < smsIndex + 1; i++) {
                    //從email開始，到sms，是所有的聯繫方式
                    //將聯繫方式的選中設為false
                    InfoMultiBean infoMultiBean = data.get(i);
                    //拿到對象，找到上一次被設為默認的那個聯繫方式，修改為false
                    MultiCheckInputBean multiCheckInputBean = (MultiCheckInputBean) infoMultiBean;
                    if (multiCheckInputBean.isDefault()) {
                        lastDefault = i;
                        multiCheckInputBean.setDefault(false);
                        break;
                    }
                }
                //然後再將本次選中的設為true，刷新這兩個item
                InfoMultiBean infoMultiBean = data.get(position);
                MultiCheckInputBean multiCheckInputBean = (MultiCheckInputBean) infoMultiBean;
                multiCheckInputBean.setDefault(true);
                infoMultiAdapter.notifyItemChanged(lastDefault);
                infoMultiAdapter.notifyItemChanged(position);
            }
        });
        return infoMultiAdapter;
    }


    public View.OnFocusChangeListener mSupplierNameChangeListener = (v, hasFocus) -> {
        if (v instanceof EditText) {
            if (!hasFocus) {
                EditText editText = (EditText) v;
                if (TextUtil.isNotEmptyOrNullOrUndefined(editText)) {
                    if (TextUtil.isNotEmptyOrNullOrUndefined(supplierName)) {
                        //當供應商名稱不為空時，是修改供應商
                        if (!editText.getText().toString().equals(supplierName)) {
                            //輸入的供應商名稱和之前的名稱不相同，說明進行了修改，需要進行查詢
                            getSupplierInfo(editText, editText.getText().toString());
                        }
                    } else {
                        getSupplierInfo(editText, editText.getText().toString());
                    }
                } else {
                    editText.setError("請輸入供應商名稱");
                }
            }
        }
    };

    /**
     * 獲取供應商聯繫方式
     *
     * @param supplierName 供應商名稱
     */
    public void getSupplierInfo(EditText editText, String supplierName) {
        Map<String, Object> map = new HashMap<>(3);
        Constant.addRestaurantId(map);
        Constant.addBrandId(map);
        map.put("supplierName", supplierName);
        mModel.getSupplierInfo(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.getData() != null) {
                            if (editText != null) {
                                editText.setError("供應商已存在，請重新輸入");
                            }
                        }
                    }
                });
    }

    ;

    /**
     * 修改供應商信息
     */
    public void updateSupplier() {
        SupplierInfoBean supplierInfoBean = getSupplierInfo(infoMultiAdapter.getData(), supplierBean);
        if (supplierInfoBean == null) {
            return;
        }
        //供應商聯繫方式不是在這個接口修改，就不傳到後台去了
        supplierInfoBean.setSupplierContacts(null);
        //修改供應商聯繫方式單獨在這個接口
        updateSupplierContact();
        //如果供應商名稱沒有修改，就不傳給後台
        if (supplierName.equals(supplierInfoBean.getSupplierName())) {
            supplierInfoBean.setSupplierName(null);
        }
        supplierInfoBean.setSupplierNo(null);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(supplierInfoBean));
        mModel.updateSupplier(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(@NonNull BaseResult info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                //供應商信息修改後，將購物車中的供應商信息修改
                                supplierInfoBean.setSupplierName(supplierName);
                                SupplyShoppingCart.getInstance().updateSupplier(supplierInfoBean);
//                                SupplyShoppingCart.getInstance().removeFoodsBySupplier(supplierBean.getId());
                                mRootView.saveSuccess();
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("保存失敗");
                            }
                        }
                    }
                });
    }

    /**
     * 刪除供應商信息
     */
    public void deleteSupplier(int supplierId) {
        mModel.deleteSupplier(supplierId)
                .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(@NonNull BaseResult info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                SupplyShoppingCart.getInstance().removeFoodsBySupplier(supplierId);
                                mRootView.saveSuccess();
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage(Constant.SAVE_FAIL);
                            }
                        }
                    }
                });
    }

    /**
     * 獲取供應商聯繫方式
     *
     * @param supplierId
     */
    public void getSupplierContact(String supplierId) {
        mModel.getSupplierContact(supplierId)
                .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(@NonNull BaseResult info) {
                        if (info != null) {
                            if (info.isSuccess() && info.getData() != null) {
                                supplierContacts = GsonUtils.jsonToList(info.getData(), SupplierInfoBean.SupplierContacts.class);
                                List<InfoMultiBean> data = infoMultiAdapter.getData();
                                for (SupplierInfoBean.SupplierContacts contacts : supplierContacts) {
                                    switch (contacts.getType()) {
                                        case Email:
                                            setChildContacts(data, contacts, emailIndex);
                                            break;
                                        case Whatsapp:
                                            setChildContacts(data, contacts, WhatsAppIndex);
                                            break;
                                        case WeChat:
                                            setChildContacts(data, contacts, weChatIndex);
                                            break;
                                        case Line:
                                            setChildContacts(data, contacts, lineIndex);
                                            break;
                                        case Kakao_Talk:
                                            setChildContacts(data, contacts, kakaoIndex);
                                            break;
                                        case SMS:
                                            setChildContacts(data, contacts, smsIndex);
                                            break;
//                                            case Efax:
//                                                data.get(efaxIndex).setShowValue(contacts.getConfigText());
//                                                break;
                                        default:
                                            break;
                                    }
                                }
                                infoMultiAdapter.notifyDataSetChanged();
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                //獲取聯繫方式失敗

                            }
                        }
                    }

                    private void setChildContacts(List<InfoMultiBean> data, SupplierInfoBean.SupplierContacts contacts, int index) {
                        InfoMultiBean infoMultiBean = data.get(index);
                        infoMultiBean.setShowValue(contacts.getConfigText());
                        if (infoMultiBean instanceof MultiCheckInputBean) {
                            MultiCheckInputBean multiCheckInputBean = (MultiCheckInputBean) infoMultiBean;
                            multiCheckInputBean.setDefault(contacts.isDefault());
                        }
                    }
                });
    }

    /**
     * 修改供應商聯繫方式
     */
    public void updateSupplierContact() {
        List<SupplierInfoBean.SupplierContacts> contacts = getContacts();
        if (contacts == null) {
            return;
        }
        if (supplierContacts != null) {
            //如果這個供應商之前有聯繫方式，則需要拿現在的聯繫方式和之前的進行對比，哪些有修改
            Iterator<SupplierInfoBean.SupplierContacts> iterator = contacts.iterator();
            while (iterator.hasNext()) {
                boolean afterHasThisContact = false;
                SupplierInfoBean.SupplierContacts nextContact = iterator.next();
                for (SupplierInfoBean.SupplierContacts supplierContact : supplierContacts) {
                    if (nextContact.getType() == supplierContact.getType()) {
                        nextContact.setId(supplierContact.getId());
                        afterHasThisContact = true;
                        break;
                    }
                }
                if (!afterHasThisContact) {
                    if (!nextContact.isDefault() && TextUtil.isEmptyOrNullOrUndefined(nextContact.getConfigText())) {
                        //之前沒有這個聯繫方式，並且不是默認的，如果這個聯繫方式是空的,就移除掉
                        iterator.remove();
                    }
                }
            }
        } else {
            deleteNullContact(contacts);
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(contacts));
        mModel.updateSupplierContact(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(@NonNull BaseResult info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("修改聯繫方式失敗");
                            }
                        }
                    }
                });
    }

    /**
     * 添加供應商
     */
    public void addSupplier() {
        SupplierInfoBean supplierInfoBean = getSupplierInfo(infoMultiAdapter.getData(), supplierBean);
        if (supplierInfoBean == null) {
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(supplierInfoBean));
        mModel.addSupplier(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(@NonNull BaseResult info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                mRootView.saveSuccess();
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("保存失敗");
                            }
                        }
                    }
                });
    }

    /**
     * 獲取輸入的供應商信息
     *
     * @param infoMultiBeans
     * @param supplierInfoBean
     * @return 這個方法目前只有新增和修改供應商用，關於聯繫方式，新增是在這裡新增，修改則不是在這裡，所以需要驗證聯繫方式輸入框是不是有內容
     */
    public SupplierInfoBean getSupplierInfo(List<InfoMultiBean> infoMultiBeans, SupplierInfoBean supplierInfoBean) {
        if (supplierInfoBean == null) {
            supplierInfoBean = new SupplierInfoBean();
        }
        //供應商編號
        supplierInfoBean.setSupplierNo(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(supplierNoIndex).getShowValue()));
        //供應商名稱
        supplierInfoBean.setSupplierName(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(supplierNameIndex).getShowValue()));
        //聯繫人
        supplierInfoBean.setContacts(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(contactsIndex).getShowValue()));
        //手機號碼
        String telephone = TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(telephoneIndex).getShowValue());
        supplierInfoBean.setContactInformation(telephone);
        //地址
        supplierInfoBean.setAddress(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(addressIndex).getShowValue()));
        //餐廳信息
        supplierInfoBean.setRestaurantId(Constant.getRestaurantId());
        supplierInfoBean.setBrandId(Constant.getBrandId());
        //最低採購金額
        String minimumAmount = infoMultiBeans.get(lowPurchaseAmount).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(minimumAmount)) {
            supplierInfoBean.setMinimumAmount(Double.parseDouble(minimumAmount));
        }
        //運費
        String shipping = infoMultiBeans.get(shippingIndex).getShowValue();
        if (TextUtil.isNotEmptyOrNullOrUndefined(shipping)) {
            supplierInfoBean.setShipping(Double.parseDouble(shipping));
        }
        //供應商編號如果沒填，就設為空
        if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getSupplierNo())) {
            supplierInfoBean.setSupplierNo(null);
        }
        if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getSupplierName())) {
            mRootView.showMessage("請輸入供應商名稱");
            return null;
        } else if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getContacts())) {
            mRootView.showMessage("請輸入聯繫人");
            return null;
        } else if (TextUtil.isEmptyOrNullOrUndefined(telephone)) {
            mRootView.showMessage("請輸入聯繫人電話");
            return null;
        } else if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getAddress())) {
            mRootView.showMessage("請輸入聯繫人地址");
            return null;
        }
        if (telephone.length() != AppConstans.MOBILE_TYPE_HK_LENGTH && telephone.length() != AppConstans.MOBILE_TYPE_CH_LENGTH) {
            mRootView.showMessage("聯繫人電話格式不正確 ");
            return null;
        }
        if (telephone.length() == AppConstans.MOBILE_TYPE_CH_LENGTH) {
            if (!MatchUtils.checkMobile(telephone)) {
                mRootView.showMessage("聯繫人電話格式不正確");
                return null;
            }
        }
        List<SupplierInfoBean.SupplierContacts> contacts = getContacts();
        if (contacts == null) {
            return null;
        }
        deleteNullContact(contacts);
        supplierInfoBean.setSupplierContacts(contacts);
        supplierInfoBean.setRemarks(TextUtil.getNotNullStrAndTrim(infoMultiBeans.get(remarkIndex).getShowValue()));
        return supplierInfoBean;
    }

    private void deleteNullContact(List<SupplierInfoBean.SupplierContacts> contacts) {
        if (contacts != null) {
            Iterator<SupplierInfoBean.SupplierContacts> iterator = contacts.iterator();
            while (iterator.hasNext()) {
                SupplierInfoBean.SupplierContacts nextContact = iterator.next();
                if (!nextContact.isDefault()) {
                    if (TextUtil.isEmptyOrNullOrUndefined(nextContact.getConfigText())) {
                        //如果聯繫方式的內容是空的，則需要去掉
                        iterator.remove();
                    }
                }
            }
        }
    }

    /**
     * 獲取聯繫方式
     */
    private List<SupplierInfoBean.SupplierContacts> getContacts() {
        List<SupplierInfoBean.SupplierContacts> contacts = new ArrayList<>();
        List<InfoMultiBean> data = infoMultiAdapter.getData();

        InfoMultiBean infoMultiBean = data.get(emailIndex);
        if (infoMultiBean instanceof MultiCheckInputBean) {
            MultiCheckInputBean multiCheckInputBean = (MultiCheckInputBean) infoMultiBean;
            String email = infoMultiBean.getShowValue();
            if (TextUtil.isNotEmptyOrNullOrUndefined(email)) {
                if (!MatchUtils.isEmail(email)) {
                    mRootView.showMessage("郵箱格式不正確");
                    return null;
                } else {
                    contacts.add(new SupplierInfoBean.SupplierContacts(email, Email, multiCheckInputBean.isDefault()));
                }
            } else {
                if (multiCheckInputBean.isDefault()) {
                    mRootView.showMessage("請輸入郵箱地址");
                    return null;
                } else {
                    contacts.add(new SupplierInfoBean.SupplierContacts(email, Email, multiCheckInputBean.isDefault()));
                }
            }
        }
        addContacts(contacts, data, WhatsAppIndex, Whatsapp);
        addContacts(contacts, data, weChatIndex, WeChat);
        addContacts(contacts, data, lineIndex, Line);
        addContacts(contacts, data, kakaoIndex, Kakao_Talk);

        InfoMultiBean smsInfoMultiBean = data.get(smsIndex);
        if (smsInfoMultiBean instanceof MultiCheckInputBean) {
            MultiCheckInputBean smsMultiCheckBean = (MultiCheckInputBean) smsInfoMultiBean;
            if (smsMultiCheckBean.isDefault()) {
                //如果設置sms是默認聯繫方式，那麼需要判斷是否輸入了內容
                if (TextUtil.isNotEmptyOrNullOrUndefined(smsMultiCheckBean.getShowValue())) {
                    addContacts(contacts, data, smsIndex, SMS);
                } else {
                    mRootView.showMessage("請輸入sms");
                    return null;
                }
            } else {
                addContacts(contacts, data, smsIndex, SMS);
            }
        } else {
            addContacts(contacts, data, smsIndex, SMS);
        }
        if (supplierBean != null) {
            for (SupplierInfoBean.SupplierContacts contact : contacts) {
                contact.setSupplierId(supplierBean.getId());
            }
        }
        return contacts;
    }

    private void addContacts(List<SupplierInfoBean.SupplierContacts> contacts, List<InfoMultiBean> data, int index, int tag) {
        InfoMultiBean infoMultiBean;
        infoMultiBean = data.get(index);
        if (infoMultiBean instanceof MultiCheckInputBean) {
            MultiCheckInputBean multiCheckInputBean = (MultiCheckInputBean) infoMultiBean;
            String weChat = infoMultiBean.getShowValue();
            contacts.add(new SupplierInfoBean.SupplierContacts(weChat, tag, multiCheckInputBean.isDefault()));
        }
    }
}
