package com.zxbw.modulemain.presenter

import android.text.TextUtils
import com.zxbw.modulemain.contract.RechargeContract
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.qy.CouponsEntity
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayVerifyEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.PaymentConfig
import com.zxhl.cms.utils.UserDataUtils
import org.json.JSONObject

class RechargePresenter : RechargeContract.Presenter {

    private val mView: RechargeContract.View

    constructor(mView: RechargeContract.View) {
        this.mView = mView
    }

    override fun getFetchCard() {
        ApiClient.homeApi.getFetchallCard().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<CouponsEntity>>() {
                override fun onSuccess(result: List<CouponsEntity>?) {
                    mView.setCouponsList(result)
                    getPayList("mobileFee")
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView.setCouponsList(null)
                    getPayList("mobileFee")
                }
            })
    }

    override fun getPayList(payModel: String) {
        ApiClient.videoInfoApi.getPayConfig(payModel).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<MemberEntity>() {
                override fun onSuccess(result: MemberEntity?) {
                    if (!result?.goodsList.isNullOrEmpty()) {
                        if (result?.goodsList?.size!! >= 1) {
                            mView.setPayList(result)
                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                }
            })
    }

    override fun requestRightsAliPay(
        jumpScheme: String,
        goodsId: String,
        payType: String,
        phone: String,
        type: String,
        skill: Boolean?,
        outTradeNo: String?,
        couponId: String?,
        mobileOp: String?
    ) {
        ApiClient.userInfoAPi.aliPayRights(
            jumpScheme,
            goodsId,
            payType,
            phone,
            type,
            skill,
            outTradeNo,
            couponId,
            mobileOp
        )
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AliPayEntity>() {
                override fun onSuccess(result: AliPayEntity?) {
                    if (result != null) {
                        mView?.requestOrderSuc(result)
                    } else {
                        mView?.requestOrderFail("zfb订单支付请求成功 数据为空")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView?.verifyOrderFail("zfb订单支付请求失败 code:${code} msg:${errorMsg}")
                }
            })
    }

    override fun verifyPay(order: String?, payType: Int) {
        try {
            if (payType == 1) {
                val json = JSONObject(order)
                val obj = json.getJSONObject("alipay_trade_app_pay_response")
                val tradeOrder = obj.getString("trade_no")
                val outTradeOrder = obj.getString("out_trade_no")
                requestVerify(outTradeOrder, tradeOrder, payType)
            } else if (payType == 2) {
                val json = JSONObject(order)
                val tradeOrder = ""
                val outTradeOrder = json.getString("extData")
                requestVerify(outTradeOrder, tradeOrder, payType)
            } else if (payType == 11) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                }
            } else if (payType == 12) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                }
            } else if (payType == 13) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                }
            } else if (payType == 21) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                } else {
                    mView?.verifyOrderFail("支付成功后 订单id为null")
                }
            } else if (payType == PaymentConfig.SD_PAY) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                }
            } else if (payType == PaymentConfig.ZFB_H5_PAY||payType == PaymentConfig.WX_H5_PAY|| payType == PaymentConfig.HUI_FU_H5_PAY1|| payType == PaymentConfig.HUI_FU_H5_PAY2) {
                if (!TextUtils.isEmpty(order)) {
                    requestVerify(order ?: "", "", payType)
                }
            } else {
                mView.verifyOrderFail("支付成功后 开始校验订单异常 e:支付方式异常$payType")
            }
        } catch (e: Exception) {
            mView.verifyOrderFail("支付成功后 开始校验订单异常 e:${e.cause} msg:${e.message}")
        }
    }

    override fun appInfo() {
        ApiClient.homeApi.getAppInfo()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AppInEntity>() {
                override fun onSuccess(result: AppInEntity?) {
                    if (result != null) {
                        mView.setAppInfo(result)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    private fun requestVerify(outTradeOrder: String, tradeOrder: String, payType: Int) {
        ApiClient.userInfoAPi.verifyPay(outTradeOrder, tradeOrder, payType)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<PayVerifyEntity>() {
                override fun onSuccess(result: PayVerifyEntity) {
                    UserDataUtils.updateUserInfo(null)
                    if (TextUtils.equals("200", result.status)) {
                        mView?.verifyOrderSuc(result.payStatus)
                    } else {
                        mView?.verifyOrderFail("订单校验请求成功 校验异常${result?.status ?: -1}")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView?.verifyOrderFail("订单校验请求失败：code:${code} msg:${errorMsg}")
                }
            })
    }
}