package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.ui.bean.InfoMultiBean;
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.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;


/**
 * ================================================
 * 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;

    @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 void updateSupplier(SupplierInfoBean supplierInfoBean) {
        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("保存失敗");
                            }
                        }
                    }
                });
    }

    public void addSupplier(SupplierInfoBean supplierInfoBean) {
        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(2).getShowValue());
        supplierInfoBean.setSupplierName(infoMultiBeans.get(3).getShowValue());
        supplierInfoBean.setContacts(infoMultiBeans.get(4).getShowValue());
        supplierInfoBean.setContactInformation(infoMultiBeans.get(5).getShowValue());
        supplierInfoBean.setAddress(infoMultiBeans.get(6).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(supplierInfoBean.getContactInformation())) {
            mRootView.showMessage("請輸入聯繫人電話");
            return null;
        } else if (TextUtil.isEmptyOrNullOrUndefined(supplierInfoBean.getAddress())) {
            mRootView.showMessage("請輸入聯繫人地址");
            return null;
        }

        List<SupplierInfoBean.SupplierContacts> contacts = new ArrayList<>();

        String email = infoMultiBeans.get(9).getShowValue();
        isAddContact(contacts, email, SupplierInfoBean.SupplierContacts.Email);

        String landline = infoMultiBeans.get(10).getShowValue();
        isAddContact(contacts, landline, SupplierInfoBean.SupplierContacts.Landline);

        List<InfoMultiBean> childContacts = infoMultiBeans.get(11).getInfoMultiBeans();
        String whatsApp = childContacts.get(0).getShowValue();
        isAddContact(contacts, whatsApp, SupplierInfoBean.SupplierContacts.Whatsapp);

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

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

        String kakao = childContacts.get(3).getShowValue();
        isAddContact(contacts, kakao, SupplierInfoBean.SupplierContacts.Kakao);

        String sms = childContacts.get(4).getShowValue();
        isAddContact(contacts, sms, SupplierInfoBean.SupplierContacts.SMS);

        String efax = childContacts.get(5).getShowValue();
        isAddContact(contacts, efax, SupplierInfoBean.SupplierContacts.Efax);

        supplierInfoBean.setSupplierContacts(contacts);
        supplierInfoBean.setRemarks(infoMultiBeans.get(14).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));
        }
    }


}
