package com.zxhl.cms.pay

import android.app.Activity
import android.text.TextUtils
import android.util.Log
import com.zxhl.cms.AppContext
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.box.BoxInfoEntity
import com.zxhl.cms.net.model.box.VerifacationEntity
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayMinEntity
import com.zxhl.cms.net.model.uc.PayVerifyEntity
import com.zxhl.cms.net.model.uc.WeChatPayEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.UserDataUtils
import com.zxhl.cms.utils.WeChatPay
import org.json.JSONObject

/**
 * Created by gaoleichao on 2021/8/31
 */
class PayPresenter : PayContract.Presenter {


    private val mView: PayContract.View


    constructor(mView: PayContract.View) {
        this.mView = mView

    }

    override fun getPriceList() {
        querySwitch()
    }

    override fun getVersifacation() {
        ApiClient.homeApi.getVerfication()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<VerifacationEntity>() {
                override fun onSuccess(result: VerifacationEntity?) {
                    if (result != null) {
                        mView.setCanInvest(result?.can)
                    }
                }

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

                }
            })
    }

    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?) {

                }
            })
    }

    override fun shoprequestWechatPayOrder(
        goodsId: String,
        payType: String,
        payMode: String,
        addressId: String,
        discount: String,
        goodIds: String,
        orderNotes: String
    ) {
        ApiClient.userInfoAPi.shopwechatPay(
            goodsId,
            payType,
            payMode,
            addressId,
            discount,
            goodIds,
            orderNotes
        )
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WeChatPayEntity>() {
                override fun onSuccess(result: WeChatPayEntity?) {
                    if (result != null) {
                        EventUtils.onEvent("member_page_pay_get_order_suc")
                        mView?.setOrderNo(result?.outTradeNo)
                        WeChatPay.startWeChatPay(result, payType)
                        mView?.requestOrderSuc()
                    } else {
                        EventUtils.onEvent("member_page_pay_get_order_fail")
                        mView?.verifyOrderFail("商城微信支付请求成功 数据为空")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("member_page_pay_get_order_fail")
                    mView?.verifyOrderFail("商城微信支付请求失败 code:${code} msg:${errorMsg}")
                }
            })
    }

    override fun shoprequestAliPay(
        activity: Activity,
        goodsId: String,
        payType: String,
        payMode: String,
        addressId: String,
        discount: String,
        goodIds: String,
        orderNotes: String
    ) {
        ApiClient.userInfoAPi.shopaliPay(
            goodsId,
            payType,
            payMode,
            addressId,
            discount,
            goodIds,
            orderNotes
        )
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AliPayEntity>() {
                override fun onSuccess(result: AliPayEntity?) {
                    if (result != null) {
                        mView?.setOrderNo(result?.outTradeNo)
                        if (payType == "13") {
                            SettingPreference.setOutTradeNo(result?.outTradeNo)
                            JumpUtils.h5Jump("https://api.minpayment.com/pay.do?sendMsg=" + result.wakeup)
                        } else if (payType == "21") {
                            SettingPreference.setOutTradeNo(result?.outTradeNo)
                            mView.requestH5OrderSuc(result.outTradeNo ?: "")
                        }else{
                            AlipayServer.payV2(activity, result.wakeup!!)
                        }
                        mView?.requestOrderSuc()
                    } else {
                        EventUtils.onEvent("member_page_pay_get_order_fail")
                        mView?.verifyOrderFail("商城zfb支付请求成功 数据为空")
                    }
                }

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

    override fun requestMiniProgrom(goodsId: String, payType: String, payMode: String) {
        ApiClient.userInfoAPi.MinPay(goodsId, payType, "", "", payMode)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<PayMinEntity>() {
                override fun onSuccess(result: PayMinEntity?) {
                    if (result != null) {
                        EventUtils.onEvent("member_page_pay_get_order_suc")
                        mView?.setOrderNo(result?.outTradeNo)
                        SettingPreference.setOutTradeNo(result?.outTradeNo)
                        if (payType == "13") {
                            JumpUtils.h5Jump("https://api.minpayment.com/pay.do?sendMsg=" + result.wakeup)
                        } else if (payType == "21") {
                            mView.requestH5OrderSuc(result.outTradeNo ?: "")
                        }
                        //WeChatPay.startWeChatProgromPay(result, payType)
                        mView?.requestOrderSuc()
                    } else {
                        EventUtils.onEvent("member_page_pay_get_order_fail")
                        mView?.verifyOrderFail("敏支付请求成功 数据为空")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("member_page_pay_get_order_fail")
                    Log.e("MXL", "调小程序" + "e:" + e + "code" + code + "errorMsg:" + errorMsg)
                    mView?.verifyOrderFail("敏支付请求失败 code:${code} msg:${errorMsg}")
                }
            })
    }

    override fun requestWechatPayOrder(goodsId: String, payType: String) {
        ApiClient.userInfoAPi.wechatPay(goodsId, payType, "", "", "6")
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<WeChatPayEntity>() {
                override fun onSuccess(result: WeChatPayEntity?) {
                    if (result != null) {
                        EventUtils.onEvent("member_page_pay_get_order_suc")
                        mView?.setOrderNo(result?.outTradeNo)
                        WeChatPay.startWeChatPay(result, payType)
                        mView?.requestOrderSuc()
                    } else {
                        EventUtils.onEvent("member_page_pay_get_order_fail")
                        mView?.verifyOrderFail("微信支付请求成功 数据为空")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("member_page_pay_get_order_fail")
                    mView?.verifyOrderFail("微信支付请求失败 code:${code} msg:${errorMsg}")
                }
            })
    }

    override fun requestAliPay(
        activity: Activity,
        goodsId: String,
        payType: String,
        payMode: String
    ) {
        ApiClient.userInfoAPi.aliPay(goodsId, payType, "", "", payMode)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AliPayEntity>() {
                override fun onSuccess(result: AliPayEntity?) {
                    if (result != null) {
                        mView?.setOrderNo(result?.outTradeNo)
                        AlipayServer.payV2(activity, result.wakeup!!)
                        mView?.requestOrderSuc()
                    } else {
                        EventUtils.onEvent("member_page_pay_get_order_fail")
                        mView?.verifyOrderFail("zfb支付请求成功 数据为空")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("member_page_pay_get_order_fail")
                    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")
                }
            }
        } catch (e: Exception) {
            mView?.verifyOrderFail("支付成功后 开始校验订单异常 e:${e.cause} msg:${e.message}")
        }

    }

    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 (result != null && TextUtils.equals("200", result.status)) {
                        mView?.verifyOrderSuc(result.payStatus)
                        EventUtils.onEvent("member_page_pay_suc", result.toString())
                    } else {
                        EventUtils.onEvent("member_page_pay_query_order_fail", result.toString())
                        mView?.verifyOrderFail("订单校验请求成功 校验异常${result?.status ?: -1}")
                    }
                }

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

    private fun querySwitch() {
        ApiClient.userInfoAPi.queryPaySwitch().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<PayVerifyEntity>() {
                override fun onSuccess(result: PayVerifyEntity?) {
                    if (TextUtils.equals(result?.popUpSwitch, "1")) {
                        getPriceData(false)
                    } else {
                        getPriceData(true)
                    }
                }

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

    private fun getPriceData(isDouble: Boolean) {
        ApiClient.videoInfoApi.getPayConfig().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<MemberEntity>() {
                override fun onSuccess(result: MemberEntity?) {
                    if ((result?.goodsList?.size ?: 0) > 0) {
                        if (isDouble) {
                            mView?.updatePriceList(result?.goodsList!!)
                        } else {
                            val mList: MutableList<MemberEntity.ProductDetail> = ArrayList()
                            result?.goodsList?.forEach {
                                if (TextUtils.equals(it.days, "3650")) {
                                    mList?.add(it)
                                }
                            }
                            mView?.updatePriceList(mList)
                        }
                    }
                }

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


}