package com.datarecovery.master.module.member;

import android.text.TextUtils;
import android.util.Pair;

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

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.common.runtime.ActivityUtil;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.R;
import com.datarecovery.master.data.api.bean.MemberGoodsBean;
import com.datarecovery.master.data.api.bean.PayOptionsBean;
import com.datarecovery.master.data.api.bean.WechatPaymentSignBean;
import com.datarecovery.master.data.api.response.MemberDetailResponse;
import com.datarecovery.master.data.api.response.MemberPayResponse;
import com.datarecovery.master.data.consts.Constants;
import com.datarecovery.master.data.repositories.AccountRepository;
import com.datarecovery.master.data.repositories.MemberRepository;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.login.LoginActivity;
import com.datarecovery.master.module.member.bean.EvaluateBean;
import com.datarecovery.master.module.member.bean.SuperScenesBean;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.OrderReportHelper;
import com.datarecovery.master.utils.RxHttpHandler;
import com.datarecovery.master.utils.ToastUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.rxjava.utils.RxJavaUtil;
import dagger.hilt.android.lifecycle.HiltViewModel;
import plus.pay.AgilePay;
import plus.pay.alipay.AlipayInfo;
import plus.pay.listener.AgilePayState;
import plus.pay.wxpay.WXpayInfo;


@HiltViewModel
public class MemberViewModel extends BaseViewModel {


    private final MemberRepository memberRepository;
    private final MutableLiveData<String> subscribeTxt = new MutableLiveData<>();

    private final MutableLiveData<List<MemberGoodsBean>> memberGoodsList = new MutableLiveData<>();
    private final MutableLiveData<List<PayOptionsBean>> payWayList = new MutableLiveData<>();
    private final MutableLiveData<MemberGoodsBean> selectBean = new MutableLiveData<>();
    private final MutableLiveData<String> serviceContentTxt = new MutableLiveData<>();
    private final MutableLiveData<List<EvaluateBean>> evaluateList = new MutableLiveData<>();

    private final SingleLiveEvent<String> onSubscribeSuccessEvent = new SingleLiveEvent<>();
    private final Gson gson;
    private final AccountRepository accountRepository;
    private List<SuperScenesBean> superScenesBeans;

    private final SingleLiveEvent<Boolean> showLoadingEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<?> goTargetActEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<?> showChoicePayWayDialog = new SingleLiveEvent<>();

    private final SingleLiveEvent<Pair<String, String>> showWxQRPaymentEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<Pair<String, String>> showAliQRPaymentEvent = new SingleLiveEvent<>();

    private final HashMap<String, MemberGoodsBean> orderIdItemMap = new HashMap<>();
    @MemberType
    private String memberType;

    @Inject
    public MemberViewModel(MemberRepository memberRepository, Gson gson, AccountRepository accountRepository) {
        this.memberRepository = memberRepository;
        this.accountRepository = accountRepository;
        this.gson = gson;
    }


    public LiveData<?> getGoTargetActEvent() {
        return goTargetActEvent;
    }

    public String getMemberType() {
        return memberType;
    }

    public LiveData<String> getSubscribeTxt() {
        return subscribeTxt;
    }

    public LiveData<Pair<String, String>> getShowWxQRPaymentEvent() {
        return showWxQRPaymentEvent;
    }

    public LiveData<Pair<String, String>> getShowAliQRPaymentEvent() {
        return showAliQRPaymentEvent;
    }

    public LiveData<Boolean> getShowLoadingEvent() {
        return showLoadingEvent;
    }

    public LiveData<?> getShowChoicePayWayDialog() {
        return showChoicePayWayDialog;
    }

    public LiveData<String> getServiceContentTxt() {
        return serviceContentTxt;
    }

    public LiveData<MemberGoodsBean> getSelectBean() {
        return selectBean;
    }

    public void setSelectBean(MemberGoodsBean bean) {
        selectBean.setValue(bean);
    }

    public LiveData<List<MemberGoodsBean>> getMemberGoodsList() {
        return memberGoodsList;
    }

    public LiveData<List<PayOptionsBean>> getPayWayList() {
        return payWayList;
    }

    public List<SuperScenesBean> getSuperScenesBeans() {
        return superScenesBeans;
    }

    public LiveData<List<EvaluateBean>> getEvaluateList() {
        return evaluateList;
    }

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

    public void setMemberType(@MemberType String type) {
        this.memberType = type;
        if (Objects.equals(memberType, MemberType.APP_IMAGE_CLEAN)) {
            subscribeTxt.setValue(ContextUtil.getContext().getString(R.string.member_clear_buy));
        } else {
            subscribeTxt.setValue(ContextUtil.getContext().getString(R.string.member_recover_buy));
        }
        initScenes();
        initCommentData();
        refreshMemberDetail();
    }

    private void initCommentData() {
        List<EvaluateBean> evaluateBeans = new ArrayList<>();
        evaluateBeans.add(new EvaluateBean(R.drawable.icon_evaluate_1, "冬季温暖优雅", "我非常满意数据恢复服务的效果。他们专业的团队帮助我成功恢复了丢失的文件，让我感到非常安心和放心。他们高效的工作速度和专业的技术水平让我对他们的服务印象深刻。强烈推荐！"));
        evaluateBeans.add(new EvaluateBean(R.drawable.icon_evaluate_2, "Starlight99", "我遇到了数据丢失的问题，但幸运的是找到了文件数据恢复大师。他们的技术团队非常专业，通过他们的努力，我成功地恢复了关键文件。他们提供的服务超出了我的期望，我对他们的工作非常满意。如果您需要数据恢复，我强烈推荐选择他们！"));
        evaluateBeans.add(new EvaluateBean(R.drawable.icon_evaluate_3, "FreeSpirit777", "文件数据恢复大师为我提供了出色的帮助。他们的团队非常耐心地解释了整个恢复过程，并及时与我沟通进展。最重要的是，他们成功地找回了我认为已经永远丢失的数据。感谢他们的专业和高效服务！"));
        evaluateList.setValue(evaluateBeans);
    }

    private void initScenes() {
        superScenesBeans = new ArrayList<>();
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_1, R.string.scenes_message_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_2, R.string.scenes_friend_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_3, R.string.scenes_img_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_4, R.string.scenes_file_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_5, R.string.scenes_video_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_6, R.string.scenes_audio_recover));
        superScenesBeans.add(new SuperScenesBean(R.drawable.icon_scenes_7, R.string.scenes_more, ContextUtil.getContext().getString(R.string.stay_tuned)));
    }


    public void refreshMemberDetail() {
        if (TextUtils.isEmpty(memberType)) {
            return;
        }
        memberRepository.memberDetail(memberType)
                .map(memberDetailResponse -> {
                    List<MemberGoodsBean> list = memberDetailResponse.getList();
                    if (list != null && !list.isEmpty()) {
                        for (MemberGoodsBean bean : list) {
                            if (Objects.equals(bean.getAuths(), MemberType.APP_WX_MESSAGE_RECOVER)) {
                                bean.setScenesArray(new String[]{"微信好友误删", "微信信息恢复", "导出微信记录", "左滑误删消息"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_WX_FRIEND_RECOVER)) {
                                bean.setScenesArray(new String[]{"微信好友被删", "微信好友找回", "恢复恢复好友"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_IMAGE_RECOVER)) {
                                bean.setScenesArray(new String[]{"相册误删图片", "手机图片丢失", "手机照片找回"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_FILE_RECOVER)) {
                                bean.setScenesArray(new String[]{"手机文件清理", "多类型文件找回", "微信/QQ文件找回"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_VIDEO_RECOVER)) {
                                bean.setScenesArray(new String[]{"误删手机视频", "手机视频丢失", "手机视频找回"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_AUDIO_RECOVER)) {
                                bean.setScenesArray(new String[]{"误删手机音频", "手机音频丢失", "手机音频找回"});
                            } else if (Objects.equals(bean.getAuths(), MemberType.APP_IMAGE_CLEAN)) {
                                bean.setScenesArray(new String[]{"手机图片彻底删除", "选择清除手机图片", "扫描手机图片"});
                            }
                        }
                    }
                    return memberDetailResponse;
                })
                .subscribe(new SingleObserver<MemberDetailResponse>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(@NonNull MemberDetailResponse memberDetailResponse) {
                        memberGoodsList.setValue(memberDetailResponse.getList());
                        payWayList.setValue(memberDetailResponse.getPayOptions());
                        serviceContentTxt.setValue(memberDetailResponse.getDescription());
                    }

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

    public boolean isMember() {
        return false;
    }

    public MemberGoodsBean getMostBuyItem() {
        List<MemberGoodsBean> memberBeans = memberGoodsList.getValue();
        if (memberBeans == null) {
            return null;
        }
        for (MemberGoodsBean memberBean : memberBeans) {
            if (Objects.equals(memberBean.getAuths(), MemberType.APP_SUPER_RECOVER)) {
                return memberBean;
            }
        }
        return null;
    }

    public void setCurrentSelectedMember(MemberGoodsBean memberBean) {
        if (Objects.equals(memberBean, selectBean.getValue())) {
            return;
        }
        selectBean.setValue(memberBean);
    }

    public void onRetainMemberSubscribeClick() {
//        if (!BoxingUtil.boxing(accountRepository.getIsLogin().getValue())) {
//            ToastUtil.show(R.string.no_login, ToastUtil.LENGTH_SHORT);
//            LoginActivity.start(ActivityUtil.getTopActivity());
//            return;
//        }
        MemberGoodsBean mostBuyItem = getMostBuyItem();
        if (mostBuyItem == null) {
            return;
        }
        setCurrentSelectedMember(mostBuyItem);
        //选择支付方式
        showChoicePayWayDialog.call();
    }


    public void onMemberSubscribeClick() {
//        if (!BoxingUtil.boxing(accountRepository.getIsLogin().getValue())) {
//            ToastUtil.show(R.string.no_login, ToastUtil.LENGTH_SHORT);
//            LoginActivity.start(ActivityUtil.getTopActivity());
//            return;
//        }
        MemberGoodsBean currentSelected = selectBean.getValue();
        if (currentSelected == null) {
            return;
        }
        //选择支付方式
        showChoicePayWayDialog.call();
    }


    public void submitOrder(int payPlatform, int payMethod) {
        MemberGoodsBean bean = selectBean.getValue();
        if (bean == null) {
            return;
        }
        memberRepository.requestPayOrder(bean.getId(), payPlatform, payMethod).subscribe(new SingleObserver<MemberPayResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
                showLoadingEvent.setValue(true);
            }

            @Override
            public void onSuccess(@NonNull MemberPayResponse memberPayResponse) {
                showLoadingEvent.setValue(false);
                orderIdItemMap.put(memberPayResponse.getOutTradeNo(), bean);
                if (payPlatform == 1 && payMethod == 2) {
                    onWeChatPay(memberPayResponse.getWechatPayPrepayJson(), memberPayResponse.getOutTradeNo());
                } else if (payPlatform == 4 && payMethod == 2) {
                    onWeChatScanPay(memberPayResponse.getWechatPayPrepayJson(), memberPayResponse.getOutTradeNo());
                } else if (payPlatform == 1 && payMethod == 1) {
                    onAliPay(memberPayResponse.getAlipayOrderString(), memberPayResponse.getOutTradeNo());
                } else if (payPlatform == 4 && payMethod == 1) {
                    onAliPayScan(memberPayResponse.getAlipayQrcodeHtml(), memberPayResponse.getOutTradeNo());
                }
            }

            @Override
            public void onError(@NonNull Throwable throwable) {
                throwable.printStackTrace();
                showLoadingEvent.setValue(false);
                if (throwable instanceof RxHttpHandler.ServerErrorException) {
                    RxHttpHandler.ServerErrorException serverErrorException = (RxHttpHandler.ServerErrorException) throwable;
                    if (serverErrorException.getCode() == Constants.ERROR_CODE_NO_LOGIN_ERROR) {
                        ToastUtil.show(R.string.no_login, ToastUtil.LENGTH_SHORT);
                        LoginActivity.start(ActivityUtil.getTopActivity(), getReportId());
                    } else {
                        ToastUtil.show(serverErrorException.getMsg(), ToastUtil.LENGTH_SHORT);
                    }
                } else {
                    ToastUtil.show(R.string.member_payment_failed, ToastUtil.LENGTH_SHORT);
                }
            }
        });
    }

    public String getReportId() {
        if (Objects.equals(memberType, MemberType.APP_WX_MESSAGE_RECOVER)) {
            return "hf11011";
        } else if (Objects.equals(memberType, MemberType.APP_WX_FRIEND_RECOVER)) {
            return "hf11009";
        } else if (Objects.equals(memberType, MemberType.APP_IMAGE_RECOVER)) {
            return "hf11001";
        } else if (Objects.equals(memberType, MemberType.APP_FILE_RECOVER)) {
            return "hf11003";
        } else if (Objects.equals(memberType, MemberType.APP_VIDEO_RECOVER)) {
            return "hf11005";
        } else if (Objects.equals(memberType, MemberType.APP_AUDIO_RECOVER)) {
            return "hf11007";
        } else if (Objects.equals(memberType, MemberType.APP_IMAGE_CLEAN)) {
            return "hf11013";
        }
        return null;
    }

    private void onAliPayScan(String s, String orderId) {
        showAliQRPaymentEvent.setValue(new Pair<>(s, orderId));
    }

    private void onAliPay(String s, String orderId) {
        AlipayInfo alipayInfo = new AlipayInfo();
        alipayInfo.setContent(s);
        requestSdkPay(alipayInfo, orderId, Constants.PAYMENT_WAY_ALIPAY);
    }

    private void onWeChatScanPay(String s, String orderId) {
        showWxQRPaymentEvent.setValue(new Pair<>(s, orderId));
    }

    private void onWeChatPay(String s, String orderId) {
        try {
            WechatPaymentSignBean wechatPaymentSignBean = gson.fromJson(s, WechatPaymentSignBean.class);
            WXpayInfo wXpayInfo = new WXpayInfo();
            wXpayInfo.setAppid(wechatPaymentSignBean.getAppId());
            wXpayInfo.setPartnerid(wechatPaymentSignBean.getPartnerId());
            wXpayInfo.setPrepayid(wechatPaymentSignBean.getPrePayId());
            wXpayInfo.set_package(wechatPaymentSignBean.getPackageName());
            wXpayInfo.setNoncestr(wechatPaymentSignBean.getRandomStr());
            wXpayInfo.setTimestamp(wechatPaymentSignBean.getTimeStamp());
            wXpayInfo.setSign(wechatPaymentSignBean.getSign());
            requestSdkPay(wXpayInfo, orderId, Constants.PAYMENT_WAY_WECHAT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void requestSdkPay(Object payInfo, String orderId, int payWay) {
        AgilePay.pay(payInfo, ActivityUtil.getTopActivity(), new AgilePayState() {
            @Override
            public void error(int errno, String error) {
                if (errno == 6001) {
                    //用户取消支付
                    return;
                }
                ToastUtil.show(R.string.member_payment_failed, ToastUtil.LENGTH_SHORT);
            }

            @Override
            public void payError(int errno, String error) {
                if (errno == 6001) {
                    //用户取消支付
                    return;
                }
                ToastUtil.show(R.string.member_payment_failed, ToastUtil.LENGTH_SHORT);
            }

            @Override
            public void paySuccess(String result) {
                MemberGoodsBean bean = orderIdItemMap.get(orderId);
                if (bean != null) {
                    EventHelper.reportPay(bean.getAmount(), orderId, payWay, bean.getName());
                }
                queryOrderStatus(orderId, payWay, true, false);
            }

            @Override
            public void payBefore() {

            }
        });
    }

    public @NonNull Disposable queryOrderStatus(String orderId, int payWay, boolean showLoading, boolean isReportPay) {
        MemberGoodsBean memberBean = orderIdItemMap.get(orderId);
        if (memberBean != null && isReportPay) {
            OrderReportHelper.recordOrderId(memberBean.getAmount(), orderId, payWay, memberBean.getName());
        }
        return memberRepository.getPayStatus(orderId)
                .doOnSubscribe(disposable -> {
                    if (showLoading) {
                        showLoadingEvent.setValue(true);
                        addDisposable(RxJavaUtil.timer(10, TimeUnit.SECONDS, () -> showLoadingEvent.setValue(false)));
                    }
                })
                .doOnSuccess(success -> {
                    if (isReportPay) {
                        if (BoxingUtil.boxing(success) && memberBean != null) {
                            EventHelper.reportPay(memberBean.getAmount(), orderId, payWay, memberBean.getName());
                        }
                    }
                })
                .subscribe(aBoolean -> {
                    showLoadingEvent.setValue(false);
                    if (BoxingUtil.boxing(aBoolean)) {
                        if (BoxingUtil.boxing(accountRepository.getIsLogin().getValue())) {
                            goTargetActEvent.call();
                        }
                        onSubscribeSuccessEvent.setValue(orderId);
                    } else {

                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    showLoadingEvent.setValue(false);
                });
    }


}
