package com.datarecovery.master.module.order;

import android.accounts.NetworkErrorException;
import android.annotation.SuppressLint;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.datarecovery.master.R;
import com.datarecovery.master.data.api.bean.OrderBean;
import com.datarecovery.master.data.api.bean.PayOptions;
import com.datarecovery.master.data.api.response.OrderPageResponse;
import com.datarecovery.master.data.consts.ErrorCode;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.data.repositories.MemberRepository;
import com.datarecovery.master.data.repositories.PayRepository;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.utils.Maps;
import com.datarecovery.master.utils.ReportUtil;
import com.datarecovery.master.utils.RxHttpHandler;
import com.datarecovery.master.utils.ToastUtil;
import com.umeng.vt.diff.V;

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

import javax.inject.Inject;

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import dagger.hilt.android.lifecycle.HiltViewModel;


@HiltViewModel
public class OrderViewModel extends BaseViewModel {


    private final PayRepository payRepository;

    private final MutableLiveData<Boolean> loading = new MutableLiveData<>();

    private final SingleLiveEvent<?> refreshOrderListEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<PayOptions> showWxQRPaymentEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<PayOptions> showAliQRPaymentEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<String> onSubscribeSuccessEvent = new SingleLiveEvent<>();
    private final MemberRepository memberRepository;


    @Inject
    public OrderViewModel(PayRepository payRepository, MemberRepository memberRepository) {
        this.payRepository = payRepository;
        this.memberRepository = memberRepository;
        refreshOrderPageList();
    }

    public LiveData<String> getOnSubscribeSuccessEvent() {
        return onSubscribeSuccessEvent;
    }

    public LiveData<PayOptions> getShowWxQRPaymentEvent() {
        return showWxQRPaymentEvent;
    }

    public LiveData<PayOptions> getShowAliQRPaymentEvent() {
        return showAliQRPaymentEvent;
    }

    public LiveData<Boolean> getLoading() {
        return loading;
    }

    public LiveData<List<OrderBean>> getOrderList() {
        return payRepository.getOrderList();
    }

    public LiveData<?> getRefreshOrderListEvent() {
        return refreshOrderListEvent;
    }

    public void refreshOrderPageList() {
        payRepository.orderPage(0, 200).subscribe(new SingleObserver<OrderPageResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
            }

            @Override
            public void onSuccess(@NonNull OrderPageResponse orderPageResponse) {
                refreshOrderListEvent.call();
            }

            @Override
            public void onError(@NonNull Throwable e) {
                refreshOrderListEvent.call();
            }
        });
    }


    @SuppressLint("WrongConstant")
    public void cancelOrder(OrderBean orderBean) {
        if (orderBean == null) {
            return;
        }
        EventHelper.report(EventId.hf1001131, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(orderBean.getAuths())));
        payRepository.cancelOrder(orderBean.getId()).subscribe(new SingleObserver<Object>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
                loading.setValue(true);
            }

            @Override
            public void onSuccess(@NonNull Object o) {
                loading.setValue(false);
                refreshOrderPageList();
                ToastUtil.show(R.string.order_cancel_order_success, ToastUtil.LENGTH_SHORT);

            }

            @Override
            public void onError(@NonNull Throwable e) {
                loading.setValue(false);
                if (e instanceof NetworkErrorException) {
                    ToastUtil.show(R.string.net_error, ToastUtil.LENGTH_SHORT);
                    return;
                }
                RxHttpHandler.ServerErrorException serverErrorException
                        = e instanceof RxHttpHandler.ServerErrorException ? ((RxHttpHandler.ServerErrorException) e) : null;
                if (serverErrorException != null) {
                    if (serverErrorException.getCode() == ErrorCode.ERROR_CODE_CANCEL_ORDER_ERROR) {
                        return;
                    }
                }
                ToastUtil.show(e.getMessage(), ToastUtil.LENGTH_SHORT);
            }
        });
    }

    @SuppressLint("WrongConstant")
    public void payOrder(OrderBean orderBean) {
        if (orderBean == null) {
            return;
        }
        int payPlatform = orderBean.getPayPlatform();
        int payMethod = orderBean.getPayMethod();
        int goodsId = orderBean.getItemId();
        HashMap<String, Object> map = new HashMap<>(2);
        map.put(EventId.EVENT_ID, ReportUtil.getReportId(orderBean.getAuths()));
        if (orderBean.getPayPlatform() == 1 && orderBean.getPayMethod() == 2) {

        } else if (orderBean.getPayPlatform() == 4 && orderBean.getPayMethod() == 2) {

        } else if (orderBean.getPayPlatform() == 1 && orderBean.getPayMethod() == 1) {//支付宝
            map.put(EventId.EVENT_TYPE1, "hf11023");
        } else if (orderBean.getPayPlatform() == 4 && orderBean.getPayMethod() == 1) {//支付宝扫码
            map.put(EventId.EVENT_TYPE1, "hf11024");
        }
        EventHelper.report(EventId.hf1001132, map);
        memberRepository.payOrder(new PayOptions(
                this::addDisposable,
                goodsId,
                orderBean.getItemName(),
                orderBean.getFenAmount(),
                payPlatform,
                payMethod,
                orderBean.isPermanent(),
                orderBean.getAuths(),
                loading::setValue,
                onSubscribeSuccessEvent::setValue,
                showWxQRPaymentEvent::setValue,
                showAliQRPaymentEvent::setValue
        ));
    }


    public Disposable queryOrderStatus(String orderId, int payWay, PayOptions payOptions, boolean showLoading, boolean isReportPay) {
        return memberRepository.queryOrderStatus(orderId, payWay, payOptions, showLoading, isReportPay);
    }
}
