package com.zxhl.cms.pay


import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.*
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxhl.cms.R
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.EventUtils.onEvent
import com.zxhl.cms.widget.CenterDialog
import com.zxhl.cms.widget.LoadingDialog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_member.*
import org.greenrobot.eventbus.EventBus
import java.util.*

/**
 * Created by gaoleichao on 2021/8/30
 */
class PayActivity : BaseActivity(), PayContract.View,
    OnRecycleItemClickListener<MemberEntity.ProductDetail>, AdCallback<String> {
    override fun onClick(p0: View?) {

    }

    override fun layoutID(): Int = R.layout.activity_member

    private var mPresenter: PayContract.Presenter? = null
    private var mAdapter: PayAdapter? = null
    private var needPrice: String? = ""
    private var mLoading: LoadingDialog? = null

    private var payResultObservable: Observable<PayResultEntity>? = null
    private var ifChooseNeedPrice: Boolean? = false
    private var userCoins: Double = 0.0
    private var type: String = ""
    private var boxid: String = ""
    private var onePrice: String = ""
    private var fivePrice: String = ""
    private var page: String = ""
    private var boxPrice: String = ""
    private var newPeople: String = ""
    private var itemlayout: Int = 0

    private var selectNum: String? = ""
    private var selectPrice: String? = ""

    private var mPayFunAdapter: PaymentFunAdapter? = null;

    companion object {
        const val ALI_PAY = 1   //支付宝支付类型
        const val WECHAT_PAY = 2  //微信支付类型
        const val MINI_PROGRAM = 11  //微信支付类型
        const val MIN_PAY_PROGRAM = 13  //敏付
        const val H5_PAY = 21  //h5支付
    }

    private var pay_type: Int? = 0
    override fun before() {
        super.before()
        setStatusBarBackground(resources.getColor(R.color.transparent))
    }


    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        id_img_back?.setOnClickListener {
            finish()
        }
        id_activity_member_close?.setOnClickListener {
            finish()
        }
        id_rl_buy_bg?.setOnClickListener {
            chosseNeedPrice()
        }
        id_ll_service?.setOnClickListener {
            JumpUtils.webJump("增值服务协议", NetConfig.H5.WEB_URL_ZENGZHI_SERVICE)
        }

        mPayFunAdapter = PaymentFunAdapter(
            this
        ) { view, position, data ->
            pay_type = data.type
            mPayFunAdapter?.setPosition(position)
        }
        id_rcl_payment_list.layoutManager = LinearLayoutManager(this)
        id_rcl_payment_list.adapter = mPayFunAdapter

//        id_rl_wechat_pay?.setOnClickListener {
//            //pay_type = MIN_PAY_PROGRAM
//            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong)
//            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong_default)
//            id_img_min_choose?.setImageResource(R.drawable.icon_xuanzhong_default)
//        }
//        id_rl_min_pay?.setOnClickListener {
//            pay_type = MIN_PAY_PROGRAM
//            id_img_min_choose?.setImageResource(R.drawable.icon_xuanzhong)
//            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
//            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong_default)
//        }
//        id_rl_zfb_pay?.setOnClickListener {
//            pay_type = ALI_PAY
//            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
//            id_img_min_choose?.setImageResource(R.drawable.icon_xuanzhong_default)
//            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)
//        }
        boxid = intent?.data?.getQueryParameter("boxid") ?: ""
        needPrice = intent?.data?.getQueryParameter("price") ?: "0"
        onePrice = intent?.data?.getQueryParameter("onePrice") ?: "0"
        fivePrice = intent?.data?.getQueryParameter("fivePrice") ?: "0"
        page = intent?.data?.getQueryParameter("page") ?: ""
        boxPrice = intent?.data?.getQueryParameter("boxPrice") ?: ""
        newPeople = intent?.data?.getQueryParameter("newPeople") ?: ""

        selectNum = intent?.data?.getQueryParameter("selectNum") ?: "0"
        selectPrice = intent?.data?.getQueryParameter("selectPrice") ?: ""
        Log.e("MXL", "NeedPrice" + needPrice)
        if (!TextUtils.isEmpty(needPrice)) {
            if (needPrice?.toDouble()?.toString()?.contains(".") == true) {
                if (TextUtils.equals(needPrice?.toDouble()?.toString(), "9.9")) {
                    id_tv_need_price?.text = needPrice?.toDouble()?.toString()
                } else {
                    var priceStr = needPrice?.toDouble()?.toInt()
                    id_tv_need_price?.text = priceStr?.plus(1).toString()
                }

            } else {
                var priceStr = needPrice?.toDouble()?.toInt()
                id_tv_need_price?.text = priceStr?.toString()
            }

        }

        type = intent?.data?.getQueryParameter("type") ?: ""
        // setBootmPrice()
        id_tv_my_yu_e?.text = SettingPreference.getUserCoinNum()

        mPresenter = PayPresenter(this)

        id_ll_pay_bottom?.setOnClickListener {
            if (pay_type == 0) {
                Utils.showToast(this, "请选择支付类型")
                return@setOnClickListener
            }
            isClickPay = true
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            EventUtils.onEvent("pay_page_pay_btn", product?.cash + "")
            EventUtils.onEvent("pay_page_pay_type", "payType$pay_type")
            if (ifChooseNeedPrice!!) {
                if (pay_type == ALI_PAY) {
                    mPresenter?.requestAliPay(
                        this,
                        id_tv_need_price.text.toString(),
                        pay_type.toString(),
                        "6"
                    )
                } else if (pay_type == WECHAT_PAY) {
                    Log.e("MXL", "微信原生支付")
                    mPresenter?.requestWechatPayOrder("", pay_type.toString())
                } else if (pay_type == MINI_PROGRAM) {
                    Log.e("MXL", "微信连连支付")
                    mPresenter?.requestWechatPayOrder("", pay_type.toString())
                } else {
                    Log.e("MXL", "微信敏支付")
                    mPresenter?.requestMiniProgrom(
                        id_tv_need_price.text.toString(),
                        pay_type.toString(),
                        "6"
                    )
                }

            } else {
                if (pay_type == ALI_PAY) {
                    mPresenter?.requestAliPay(
                        this,
                        product?.goodsId ?: "",
                        pay_type.toString(),
                        "6"
                    )
                } else if (pay_type == WECHAT_PAY) {
                    Log.e("MXL", "2微信原生支付")
                    mPresenter?.requestWechatPayOrder(
                        product?.goodsId ?: "",
                        pay_type.toString()
                    )
                } else if (pay_type == MINI_PROGRAM) {
                    Log.e("MXL", "2微信连连支付")
                    mPresenter?.requestWechatPayOrder(
                        product?.goodsId ?: "",
                        pay_type.toString()
                    )
                } else {
                    Log.e("MXL", "2支付宝敏支付")
                    mPresenter?.requestMiniProgrom(
                        product?.goodsId ?: "",
                        pay_type.toString(),
                        "6"
                    )
                }

            }

        }

        payResultObservable = RxBus.get().register(Constant.PAY_RESULT, PayResultEntity::class.java)
        payResultObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<PayResultEntity> { obj ->
                MainLooper?.get()?.postDelayed(Runnable {
                    mHandler?.removeCallbacksAndMessages(null)
                }, 1000)
                Log.d("qqbs", "verifyPay:${obj.txt}")
                //println("verifyPay payResultObservable------------------------------- order:${obj.txt}")
                if (obj.isPaySuc) {
                    if (boxid.equals("-3")) {
                        onEvent("9.9_pay_sucess", "9.9付款成功")
                    }
                    onEvent("pay_page_pay_query_order", "付款成功")
                    mPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    if (boxid.equals("-3")) {
                        onEvent("9.9_pay_fail", "9.9付款失败")
                    }
                    //支付宝支付
                    if (obj.payType == 1) {
                        if (obj.payStatus == "6001") {
                            onEvent("zfb_pay_cancel")
                        } else {
                            onEvent("zfb_pay_error", obj.payStatus + " msg:" + obj.txt)
                        }
                    } else {
                        onEvent("wx_pay_error", obj.txt)
                    }
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })

        id_activity_member_pri?.setOnClickListener {
            JumpUtils.webJump("隐私协议", NetConfig.H5.WEB_URL_PRIVACY)
        }

        id_activity_member_user?.setOnClickListener {
            JumpUtils.webJump("用户协议", NetConfig.H5.WEB_URL_USER)
        }

        EventUtils.onEvent("pay_page_show", "充值页展示")
        EventUtils.onEvent("member_page_show")
        if (Constant.Switch.isOpenPayTips) {
            var payTipsShowNum = SettingPreference.getPayTipsShowNum()
            if (payTipsShowNum < 3) {
                CenterDialog.showLotteryRuleDialog(this)
                SettingPreference.setPayTipsShowNum(payTipsShowNum + 1)
            }
        }
    }

    fun checkChoose() {
        if (needPrice.equals("0")) {
            id_rl_buy_bg?.visibility = View.GONE
            chooseOtherPrice()
        } else {
            id_rl_buy_bg?.visibility = View.VISIBLE
            chosseNeedPrice()
        }
    }

    override fun data() {
        super.data()
        mPresenter?.appInfo()
        mPresenter?.getPriceList()

    }


    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {
        if (!data.isNullOrEmpty()) {
            if (data.size >= 4 && !TextUtils.isEmpty(data[3].buttonText)) {
                itemlayout = 1
            } else {
                itemlayout = 0
            }
        }
        mAdapter = PayAdapter(this, itemlayout)
//        val widthScreen = windowManager?.defaultDisplay?.width
//        val widthDecoration = (widthScreen!! - Utils.dip2px(20 * 2) - Utils.dip2px(93 * 3)) / 6
        val gridLayoutManager: GridLayoutManager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        id_activity_member_list?.layoutManager = gridLayoutManager
        id_activity_member_list?.adapter = mAdapter

        mAdapter?.clear()
        mAdapter?.appendToList(data)
        checkChoose()

        mAdapter?.notifyDataSetChanged()
    }


    private var product: MemberEntity.ProductDetail? = null


    override fun onItemClick(view: View?, position: Int, data: MemberEntity.ProductDetail?) {
        this.product = data
        ifChooseNeedPrice = false

        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg)
        EventUtils.onEvent("member_page_item_click", data?.cash + "")
    }

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)
        } else {
            mLoading?.setResult(false, "支付失败", 1000)
            if (!Constant.NewUserBox.firstBoxId.isNullOrEmpty() && boxid == Constant.NewUserBox.firstBoxId) {
                Constant.NewUserBox.isOpenGuideBox = true
            }
        }

    }

    fun setBootmPrice() {
        if (ifChooseNeedPrice!!) {
            id_activity_member_btn?.text = needPrice
        } else {
            id_activity_member_btn?.text = product?.title
        }
    }

    override fun verifyOrderFail(errorMsg: String) {
        onEvent("pay_fail", errorMsg)
        showResultLoading(false)
    }

    override fun requestOrderSuc() {
        mLoading?.setLoading("正在支付")
    }

    override fun requestH5OrderSuc(form: String) {
        if (form.isEmpty()) {
            onEvent("h5_pay_error")
            showResultLoading(false)
        } else {
            loadH5Pay(form)
        }
    }

    override fun verifyOrderSuc(orsder: String) {
        Log.e("MXL", "充值成功，更新余额")
        //  RxBus.get().post(Constant.finish_activity, 1)
        onEvent("pay_suc")
        showResultLoading(true)
        UserDataUtils.updateUserInfo(this)

    }

    override fun setCanInvest(boolean: Boolean?) {
        if (boolean == true) {

        } else {
            Utils.showToast(this, "充值上限，无法充值")
        }
    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null && !result.pay_config_v2.isNullOrEmpty()) {
            mPayFunAdapter?.clear()
            mPayFunAdapter?.appendToList(result.pay_config_v2)
            for (i in result.pay_config_v2!!.indices) {
                if (result?.pay_config_v2!![i].open == 1) {
                    pay_type = result?.pay_config_v2!![i].type
                    mPayFunAdapter?.setPosition(i)
                    break
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
        id_pay_web_view?.destroy()
    }

    private var isPause = false
    override fun onResume() {
        super.onResume()
        if (isPause) {
            if (pay_type == MIN_PAY_PROGRAM || pay_type == H5_PAY) {
                //如果是敏支付或者H5支付
                mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
            } else {
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }


        }
//        id_pay_web_view?.onResume()
    }

    private var isClickPay = false;
    override fun onPause() {
        super.onPause()
        isPause = true
//        MobclickAgent.onPause(this)
        if (!Constant.NewUserBox.firstBoxId.isNullOrEmpty() && boxid == Constant.NewUserBox.firstBoxId && !isClickPay) {
            Constant.NewUserBox.isOpenGuideBox = true
        }
//        id_pay_web_view?.onPause()
    }

    fun chosseNeedPrice() {
        ifChooseNeedPrice = true
        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg_select)
        mAdapter?.setPosition(-1)
    }

    fun chooseOtherPrice() {
        mAdapter?.setPosition(0)
        ifChooseNeedPrice = false
        id_rl_buy_bg?.setBackgroundResource(R.drawable.shape_need_price_bg)

    }

    private val DELAY = 500
    private var lastClickTime: Long = 0
    override fun onResult(code: Int, result: String?) {
        id_tv_my_yu_e?.text = SettingPreference.getUserCoinNum()
        userCoins = SettingPreference.getUserCoinNum().toDoubleOrNull() ?: 0.00
        if (!TextUtils.isEmpty(needPrice) && !TextUtils.equals(needPrice, "0")) {
            var lotery = needPrice?.toDoubleOrNull() ?: 0.0
            if (userCoins.compareTo(lotery) >= 0) {
                if (Constant.Switch.isOpenLogin && !Constant.Switch.isBindLogin) {
                    //开启登录开关 并且未登录绑定
                    JumpUtils.AfterLoginJump(
                        boxid,
                        "0",
                        type,
                        onePrice.toString(),
                        fivePrice.toString(),
                        newPeople,
                        page, selectNum?.toIntOrNull() ?: 0, selectPrice?.toDoubleOrNull()
                    )
                    this.finish()
                    return
                }
                if (!Constant.NewUserBox.firstBoxId.isNullOrEmpty() && boxid == Constant.NewUserBox.firstBoxId) {
                    Constant.NewUserBox.isOpenGuideBox = false
                }
                //比较当前余额和要抽奖的余额 帮用户跳转到抽奖页面
                var currentTime = System.currentTimeMillis();
                if (currentTime - lastClickTime > DELAY) {
                    lastClickTime = currentTime
                    val payEvent = PayEvent()
                    payEvent.boxId = boxid
                    payEvent.onePrice = onePrice.toDoubleOrNull()
                    payEvent.fivePrice = fivePrice.toDoubleOrNull()
                    payEvent.newUserPrice = newPeople
                    payEvent.type = type
                    payEvent.page = page
                    payEvent.boxPrice = boxPrice
                    payEvent.selectNum = selectNum?.toInt()
                    payEvent.selectPrice = selectPrice?.toDoubleOrNull()
                    EventBus.getDefault().post(payEvent)
                    this.finish()
                    //JumpUtils.lotteryBoxJump(boxid, type, needPrice)
                }
            } else {
                if (!Constant.NewUserBox.firstBoxId.isNullOrEmpty() && boxid == Constant.NewUserBox.firstBoxId) {
                    Constant.NewUserBox.isOpenGuideBox = true
                }
            }
        }
    }

    private var mHandler: Handler = Handler {
        when (it.what) {
            0 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            }
        }
        false
    }


    private fun loadH5Pay(form: String) {
//        id_pay_web_view.visibility = View.VISIBLE
        Log.d("wxw","startTime"+System.currentTimeMillis())
        val webSettings = id_pay_web_view.settings
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.javaScriptEnabled = true
        //设置自适应屏幕，两者合用
        webSettings.useWideViewPort = true //将图片调整到适合webview的大小
        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
        //其他细节操作
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //关闭webview中缓存
        webSettings.allowFileAccess = true //设置可以访问文件
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.loadsImagesAutomatically = true //支持自动加载图片
        webSettings.defaultTextEncodingName = "utf-8" //设置编码格式
        webSettings.domStorageEnabled = true
        webSettings.allowFileAccessFromFileURLs = true;
        webSettings.allowUniversalAccessFromFileURLs = true;

        id_pay_web_view?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e("WXW", "dURL" + url.toString())
                if (url == null) return false
                try {
                    if (url.startsWith("alipays://") //支付宝
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                        return true
                    }
                } catch (e: Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    EventUtils.onEvent("h5_open_zfb_error", e.toString())
                    showResultLoading(false)
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //处理http和https开头的url
                view?.loadUrl(url)
                return false
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                Log.e("WXW", "cURL" + url.toString())
                Log.d("wxw","EndTime"+System.currentTimeMillis())
                super.onPageFinished(view, url)
                if (url?.contains(NetConfig.H5.WEB_URL_H5_PAY) == true) {
                    id_pay_web_view?.loadUrl("javascript:loadPayHtml('$form')");
                }
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                EventUtils.onEvent("h5_pay_error1", error.toString())
                showResultLoading(false)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                EventUtils.onEvent("h5_pay_error2", errorResponse.toString())
                showResultLoading(false)
            }
        }
        id_pay_web_view.loadUrl(NetConfig.H5.WEB_URL_H5_PAY)

    }

}