package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.text.InputFilter;
import android.view.inputmethod.EditorInfo;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
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.multi.InfoMultiAdapter;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
import com.gingersoft.gsa.cloud.ui.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.bean.MultiInputBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
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 java.util.ArrayList;
import java.util.List;

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.Efax;
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 telephoneIndex = 5;
    public final int addressIndex = 6;
    public final int emailIndex = 9;
    public final int childContactsIndex = 10;
    public final int smsIndex = 11;
    public final int efaxIndex = 12;
    public final int remarkIndex = 15;

    public final int WhatsAppIndex = 0;
    public final int weChatIndex = 1;
    public final int lineIndex = 2;
    public final int kakaoIndex = 3;

    private InfoMultiAdapter infoMultiAdapter;
    private SupplierInfoBean supplierBean;

    @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, "請輸入編號-默認GYS001", new InputFilter[]{new InputFilter.LengthFilter(11), new EnAndNumInputFilter()}));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "名稱", true, "請輸入名稱", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), chAndEnAndNumInputFilter}));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "聯繫人", true, "請輸入聯繫人", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), chAndEnAndNumInputFilter}));
        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, "詳細地址", true, "請輸入詳細地址", new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 20), chAndEnAndNumInputFilter}));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "接收方式"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "Email", false, "請輸入Email"));

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

        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "SMS", false, "請輸入SMS"));
        infoMultiBeans.add(new MultiInputBean(InfoMultiBean.ITEM_TYPE_INPUT, "Efax", false, "請輸入Efax"));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_LINE));
        infoMultiBeans.add(new InfoMultiBean(InfoMultiBean.ITEM_TYPE_TITLE, "備註"));

        MultiInputBean remarkInputBean = new MultiInputBean(InfoMultiBean.ITEM_MULTIPLE_INPUT_REMARK, null, false, "請輸入備註", new InputFilter[]{InputFilterUtils.getMaxLengthFilterDisChAndEn(RemarkProvider.REMARK_TEXT_LENGTH), chAndEnAndNumInputFilter});
        remarkInputBean.setMaxLength(RemarkProvider.REMARK_TEXT_LENGTH);

        infoMultiBeans.add(remarkInputBean);
        if (supplierBean != null) {
            infoMultiBeans.get(supplierNoIndex).setShowValue(supplierBean.getSupplierNo());
            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());
        }
        infoMultiAdapter = new InfoMultiAdapter(mContext, infoMultiBeans);
        return infoMultiAdapter;
    }

    public void updateSupplier() {
        SupplierInfoBean supplierInfoBean = getSupplierInfo(infoMultiAdapter.getData(), supplierBean);
        if (supplierInfoBean == null) {
            return;
        }
        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()) {
                                mRootView.saveSuccess();
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("保存失敗");
                            }
                        }
                    }
                });
    }

    /**
     * 獲取供應商聯繫方式
     *
     * @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) {
                                List<SupplierInfoBean.SupplierContacts> supplierContacts = JsonUtils.parseArray(info.getData(), SupplierInfoBean.SupplierContacts.class);
                                if (supplierContacts != null) {
                                    List<InfoMultiBean> data = infoMultiAdapter.getData();
                                    for (SupplierInfoBean.SupplierContacts contacts : supplierContacts) {
                                        switch (contacts.getType()) {
                                            case Email:
                                                data.get(emailIndex).setShowValue(contacts.getConfigText());
                                                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:
                                                data.get(smsIndex).setShowValue(contacts.getConfigText());
                                                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 kakaoIndex) {
                        List<InfoMultiBean> childContacts = data.get(childContactsIndex).getInfoMultiBeans();
                        childContacts.get(kakaoIndex).setShowValue(contacts.getConfigText());
                    }
                });
    }

    /**
     * 添加供應商
     */
    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("保存失敗");
                            }
                        }
                    }
                });
    }

    public SupplierInfoBean getSupplierInfo(List<InfoMultiBean> infoMultiBeans, SupplierInfoBean supplierInfoBean) {
        if (supplierInfoBean == null) {
            supplierInfoBean = new SupplierInfoBean();
        }
        supplierInfoBean.setSupplierNo(infoMultiBeans.get(supplierNoIndex).getShowValue());
        supplierInfoBean.setSupplierName(infoMultiBeans.get(supplierNameIndex).getShowValue());
        supplierInfoBean.setContacts(infoMultiBeans.get(contactsIndex).getShowValue());
        String telephone = infoMultiBeans.get(telephoneIndex).getShowValue();
        supplierInfoBean.setContactInformation(telephone);
        supplierInfoBean.setAddress(infoMultiBeans.get(addressIndex).getShowValue());
        supplierInfoBean.setRestaurantId(ResturantInfoManager.newInstance().getRestaurantId());
        supplierInfoBean.setBrandId(ResturantInfoManager.newInstance().getBrandId());
        if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getSupplierNo())) {
            supplierInfoBean.setSupplierNo("GYS001");
        }
        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 = new ArrayList<>();
        String email = infoMultiBeans.get(emailIndex).getShowValue();
        isAddContact(contacts, email, SupplierInfoBean.SupplierContacts.Email);
        if (TextUtil.isNotEmptyOrNullOrUndefined(email)) {
            if (!MatchUtils.isEmail(email)) {
                mRootView.showMessage("郵箱格式不正確");
                return null;
            }
        }

        List<InfoMultiBean> childContacts = infoMultiBeans.get(childContactsIndex).getInfoMultiBeans();
        String whatsApp = childContacts.get(WhatsAppIndex).getShowValue();
        isAddContact(contacts, whatsApp, Whatsapp);

        String weChat = childContacts.get(weChatIndex).getShowValue();
        isAddContact(contacts, weChat, SupplierInfoBean.SupplierContacts.WeChat);

        String line = childContacts.get(lineIndex).getShowValue();
        isAddContact(contacts, line, SupplierInfoBean.SupplierContacts.Line);

        String kakao = childContacts.get(kakaoIndex).getShowValue();
        isAddContact(contacts, kakao, Kakao_Talk);

        String sms = infoMultiBeans.get(smsIndex).getShowValue();
        isAddContact(contacts, sms, SupplierInfoBean.SupplierContacts.SMS);

        String efax = infoMultiBeans.get(efaxIndex).getShowValue();
        isAddContact(contacts, efax, SupplierInfoBean.SupplierContacts.Efax);

        supplierInfoBean.setSupplierContacts(contacts);
        supplierInfoBean.setRemarks(infoMultiBeans.get(remarkIndex).getShowValue());
        return supplierInfoBean;
    }

    private void isAddContact(List<SupplierInfoBean.SupplierContacts> contacts, String whatsApp, int whatsapp) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(whatsApp)) {
            contacts.add(new SupplierInfoBean.SupplierContacts(whatsApp, whatsapp));
        }
    }


}
