package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
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.supply_chain.mvp.bean.ConfirmOrderBean;
import com.gingersoft.supply_chain.mvp.bean.MsgConfigBean;
import com.gingersoft.supply_chain.mvp.bean.SendSupplierMsgBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.contract.SendMsgContract;
import com.google.gson.Gson;
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.HashMap;
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.Kakao_Talk;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Line;
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 12/08/2020 09:17
 * <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 SendMsgPresenter extends BasePresenter<SendMsgContract.Model, SendMsgContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private Map<String, String> qrCodeMap = new HashMap<>();
    private List<SendSupplierMsgBean> sendSupplierMsgBeans;

    @Inject
    public SendMsgPresenter(SendMsgContract.Model model, SendMsgContract.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 getPurchaseOrderQrCode(String orderId) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(qrCodeMap.get(orderId))) {
//            mRootView.loadQrCode(qrCodeMap.get(orderId));
            return;
        }
        mModel.getPurchaseOrderQrCode(orderId)
                .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.isSuccess() && info.getData() != null) {
                            qrCodeMap.put(orderId, info.getData().toString());
//                            mRootView.loadQrCode(qrCodeMap.get(orderId));
                        }
                    }
                });
    }

    static class PurchaseMsgBean {
        private int orderId;
        private int type;
        private String configText;
    }

    public void sendMsg() {
        if (sendSupplierMsgBeans == null) {
            mRootView.showMessage("供應商信息獲取失敗，請退出重試");
            return;
        }
        if (currentSelectedSupplier > sendSupplierMsgBeans.size()) {
            mRootView.showMessage("請重新選擇供應商");
            return;
        }
        SendSupplierMsgBean sendSupplierMsgBean = sendSupplierMsgBeans.get(currentSelectedSupplier);
        int checkPosition = sendSupplierMsgBean.getCheckPosition();
        List<SupplierInfoBean.SupplierContacts> supplierContacts = sendSupplierMsgBean.getSupplierContacts();
        if (supplierContacts == null) {
            mRootView.showMessage("當前供應商沒有發送方式");
            return;
        }
        if (checkPosition >= supplierContacts.size()) {
            mRootView.showMessage("請重新選擇供應商的發送方式");
            return;
        }
        int sendType = supplierContacts.get(checkPosition).getType();
        PurchaseMsgBean purchaseMsgBean = new PurchaseMsgBean();
        purchaseMsgBean.orderId = sendSupplierMsgBean.getOrderId();
        purchaseMsgBean.type = sendType;
        purchaseMsgBean.configText = supplierContacts.get(checkPosition).getConfigText();
        if (qrCodeMap.get(purchaseMsgBean.orderId + "") != null) {
            sendMsgByType(sendType, purchaseMsgBean);
        } else {
            sendMsgByOrderIdAndType(purchaseMsgBean, sendType);
        }
    }

    public void sendMsgByOrderIdAndType(PurchaseMsgBean purchaseMsgBean, int sendType) {
        mModel.senMsg(RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseMsgBean)))
                .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.isSuccess() && info.getData() != null) {
                            MsgConfigBean msgConfigBean = GsonUtils.GsonToBean(info.getData(), MsgConfigBean.class);
                            qrCodeMap.put(purchaseMsgBean.orderId + "", msgConfigBean.getConfigText());
                            if (sendType == Whatsapp) {
                                mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Whatsapp);
                            } else if (sendType == WeChat) {
                                mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), WeChat);
                            } else if (sendType == Line) {
                                mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Line);
                            } else if (sendType == Kakao_Talk) {
                                mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Kakao_Talk);
                            }
                            mRootView.sendSuccess();
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage("發送失敗，請切換發送方式重試");
                        }
                    }
                });
    }

    private void sendMsgByType(int sendType, PurchaseMsgBean purchaseMsgBean) {
        if (sendType == Whatsapp) {
            mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Whatsapp);
            mRootView.sendSuccess();
        } else if (sendType == WeChat) {
            mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), WeChat);
            mRootView.sendSuccess();
        } else if (sendType == Line) {
            mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Line);
            mRootView.sendSuccess();
        } else if (sendType == Kakao_Talk) {
            mRootView.shareThirdApp(qrCodeMap.get(purchaseMsgBean.orderId + ""), Kakao_Talk);
            mRootView.sendSuccess();
        } else {
            sendMsgByOrderIdAndType(purchaseMsgBean, sendType);
        }
    }

    public void getSupplierListByOrders(List<ConfirmOrderBean.PurchaseOrder> purchaseOrders) {
        //將訂單信息轉為用於顯示的供應商信息
        if (purchaseOrders != null) {
            sendSupplierMsgBeans = new ArrayList<>();
            for (ConfirmOrderBean.PurchaseOrder purchaseOrder : purchaseOrders) {
                SendSupplierMsgBean sendSupplierMsgBean = new SendSupplierMsgBean();
                sendSupplierMsgBean.setId(purchaseOrder.getSupplierId());
                sendSupplierMsgBean.setOrderId(purchaseOrder.getId());
                sendSupplierMsgBean.setSupplierName(purchaseOrder.getSupplierName());
                sendSupplierMsgBeans.add(sendSupplierMsgBean);
            }
            if (sendSupplierMsgBeans.size() > 0) {
                //獲取第一個供應商的聯繫方式
                getContactsBySupplier(0);
            }
        } else {
            mRootView.showMessage("未獲取到訂單信息");
            mRootView.killMyself();
        }
    }

    /**
     * 當前選中的供應商
     */
    private int currentSelectedSupplier;

    public int getCurrentSelectedSupplier() {
        return currentSelectedSupplier;
    }

    /**
     * 獲取供應商聯繫方式
     *
     * @param supplierIndex 供應商在集合中的下標，方便將聯繫方式插入到集合中
     */
    public void getContactsBySupplier(int supplierIndex) {
        String supplierId;
        if (sendSupplierMsgBeans != null && sendSupplierMsgBeans.size() > supplierIndex) {
            currentSelectedSupplier = supplierIndex;
            supplierId = sendSupplierMsgBeans.get(supplierIndex).getId() + "";
            List<SupplierInfoBean.SupplierContacts> supplierContacts = sendSupplierMsgBeans.get(supplierIndex).getSupplierContacts();
            for (SendSupplierMsgBean sendSupplierMsgBean : sendSupplierMsgBeans) {
                sendSupplierMsgBean.setOpen(false);
            }
            sendSupplierMsgBeans.get(supplierIndex).setOpen(true);
            if (supplierContacts != null) {
                //如果已有聯繫方式，就不用調用接口
                if (supplierContacts.size() <= 0) {
                    mRootView.showMessage("當前供應商沒有聯繫方式");
                    mRootView.loadSupplierList(sendSupplierMsgBeans);
                    return;
                } else {
//                    getPurchaseOrderQrCode(sendSupplierMsgBeans.get(supplierIndex).getOrderId() + "");
                    mRootView.loadSupplierList(sendSupplierMsgBeans);
                }
            }
        } else {
//            mRootView.showMessage("未獲取到供應商聯繫方式");
            return;
        }
        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) {
                                    for (int i = 0; i < supplierContacts.size(); i++) {
                                        if (supplierContacts.get(i).isDefault()) {
                                            sendSupplierMsgBeans.get(supplierIndex).setCheckPosition(i);
                                            break;
                                        }
                                    }
                                }
                                SendSupplierMsgBean sendSupplierMsgBean = sendSupplierMsgBeans.get(supplierIndex);
                                sendSupplierMsgBean.setSupplierContacts(supplierContacts);
//                                getPurchaseOrderQrCode(sendSupplierMsgBean.getOrderId() + "");
                                mRootView.loadSupplierList(sendSupplierMsgBeans);
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                //獲取聯繫方式失敗
                                mRootView.showMessage("獲取聯繫方式失敗或供應商沒有聯繫方式");
                            }
                        } else {
                            mRootView.showMessage("獲取聯繫方式失敗");
                        }
                    }
                });
    }
}
