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

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

    /**
     * 跟進訂單id和發送類型發送消息
     * @param purchaseMsgBean 發送消息類
     * @param 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().replace("\\n", "\n"));
                            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("發送失敗，請切換發送方式重試");
                        }
                    }
                });
    }

    /**
     * 獲取發送到供應商的消息內容並保存
     * @param orderId 訂單id
     */
    public void getSendMsgAndSave(int orderId) {
        PurchaseMsgBean purchaseMsgBean = new PurchaseMsgBean();
        purchaseMsgBean.orderId = orderId;
        purchaseMsgBean.type = SupplierInfoBean.SupplierContacts.Whatsapp;
        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(orderId + "", msgConfigBean.getConfigText().replace("\\n", "\n"));
                        }
                    }
                });
    }

    /**
     * 根據不同的類型發送消息
     * @param sendType 發送類型
     * @param purchaseMsgBean 發送類
     */
    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);
        }
    }

    /**
     * 獲取發送url
     *
     * @return
     */
    public String getSendUrl() {
        SendSupplierMsgBean sendSupplierMsgBean = sendSupplierMsgBeans.get(currentSelectedSupplier);
        return qrCodeMap.get(sendSupplierMsgBean.getOrderId() + "");
    }

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

    public void setSendSuccess() {
        SendSupplierMsgBean sendSupplierMsgBean = sendSupplierMsgBeans.get(currentSelectedSupplier);
        sendSupplierMsgBean.setSend(true);
    }

    /**
     * 獲取供應商聯繫方式
     *
     * @param supplierIndex 供應商在集合中的下標，方便將聯繫方式插入到集合中
     */
    public void getContactsBySupplier(int supplierIndex) {
        String supplierId;
        if (sendSupplierMsgBeans != null && sendSupplierMsgBeans.size() > supplierIndex) {
            //切換當前選中
            currentSelectedSupplier = supplierIndex;
            //拿到供應商id
            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 {
                    mRootView.loadSupplierList(sendSupplierMsgBeans);
                    //通過聯繫方式獲取發送內容，然後保存
                    getSendMsgAndSave(sendSupplierMsgBeans.get(supplierIndex).getOrderId());
                }
            }
        } else {
            mRootView.backToOrderList();
            return;
        }
        getSupplierContactById(supplierIndex, supplierId);
    }

    /**
     * 跟進供應商id 獲取供應商聯繫方式
     *
     * @param supplierIndex 供應商下標，獲取到聯繫方式之後刷新
     * @param supplierId    供應商id
     */
    private void getSupplierContactById(int supplierIndex, 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) {
                                    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);
                                mRootView.loadSupplierList(sendSupplierMsgBeans);
                                //通過聯繫方式獲取發送內容，然後保存
                                getSendMsgAndSave(sendSupplierMsgBeans.get(supplierIndex).getOrderId());
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                //獲取聯繫方式失敗
                                mRootView.showMessage("獲取聯繫方式失敗或供應商沒有聯繫方式");
                            }
                        } else {
                            mRootView.showMessage("獲取聯繫方式失敗");
                        }
                    }
                });
    }
}
