package com.zxhl.cms.widget


import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zxhl.cms.R
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.pay.PayPresenter
import com.zxhl.cms.pay.StarCoinPayActivity
import com.zxhl.cms.pay.StarCoinPayAdapter
import com.zxhl.cms.utils.*
import com.zxhl.novel.utils.server.PayResultEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer

object PayDialog : PayContract.View, OnRecycleItemClickListener<MemberEntity.ProductDetail>,
    AdCallback<String> {
    private var mContext: Context? = null
    private var mDialog: Dialog? = null
    private var mPresenter: PayPresenter? = null
    private var mAdapter: StarCoinPayAdapter? = null
    private var mLoading: LoadingDialog? = null
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var pay_type = 0
    private var tv_pay_service: TextView? = null
    private var id_activity_coin_list: RecyclerView? = null
    private var id_rl_zfb_pay: RelativeLayout? = null
    private var id_rl_wechat_pay: RelativeLayout? = null
    private var id_img_wechat: ImageView? = null
    private var id_img_ali: ImageView? = null
    private var product: MemberEntity.ProductDetail? = null
    private var id_tv_my_coin_num: TextView? = null
    private var id_ll_pay_bottom: LinearLayout? = null
    private var id_rl_pay_dialog: RelativeLayout? = null

    fun showPayDialog(context: Context?) {
        if (context == null) {
            return
        }
        this.mContext = context
        mPresenter = PayPresenter(this)
        mDialog = Dialog(context, R.style.CenterCompatDialogTheme)
        val mDialogView =
            CenterDialog.showBottomDialog(
                R.layout.dialog_layout_pay,
                context,
                mDialog!!,
                0,
                Gravity.CENTER
            )
        mLoading = LoadingDialog.getLoadingDialog(
            mContext,
            mContext!!.resources.getString(R.string.wait_ing),
            false,
            false
        )
        tv_pay_service = mDialogView.findViewById(R.id.id_tv_pay_service)
        id_activity_coin_list = mDialogView.findViewById(R.id.id_activity_coin_list)
        id_rl_zfb_pay = mDialogView.findViewById(R.id.id_rl_zfb_pay)
        id_rl_wechat_pay = mDialogView.findViewById(R.id.id_rl_wechat_pay)
        id_img_wechat = mDialogView.findViewById(R.id.id_img_wechat)
        id_img_ali = mDialogView.findViewById(R.id.id_img_ali)
        id_tv_my_coin_num = mDialogView.findViewById(R.id.id_tv_my_coin_num)
        id_ll_pay_bottom = mDialogView.findViewById(R.id.id_ll_pay_bottom)
        id_rl_pay_dialog = mDialogView.findViewById(R.id.id_rl_pay_dialog)
        payResultObservable = RxBus.get().register(Constant.PAY_RESULT, PayResultEntity::class.java)
        payResultObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<PayResultEntity> { obj ->
                Log.d("qqbs", "verifyPay:${obj.txt}")
                LogUtils.d("verifyPay payResultObservable------------------------------- order:${obj.txt}")
                if (obj.isPaySuc) {
                    EventUtils.onEvent("pay_page_pay_query_order", "付款成功")
                    mPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })
        id_rl_pay_dialog?.setOnClickListener {
            dismiss()
        }
        tv_pay_service?.setOnClickListener {
            JumpUtils.webJump("充值服务协议", NetConfig.H5.WEB_URL_BUYER_KNOW)
        }
        id_rl_wechat_pay?.setOnClickListener {
            pay_type = StarCoinPayActivity.MINI_PROGRAM
            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong)
            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong_default)
        }
        id_rl_zfb_pay?.setOnClickListener {
            pay_type = StarCoinPayActivity.ALI_PAY
            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)

        }
        id_ll_pay_bottom?.setOnClickListener(object : NoDoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                if (pay_type == 0) {
                    Utils.showToast(mContext, "请选择支付类型")
                    return
                }
                mLoading?.setLoading("请稍后")
                mLoading?.show()
                EventUtils.onEvent("CoinRechargeClick", "点击星币充值")

                if (pay_type == 1) {
                    mPresenter?.requestAliPay(
                        mContext as Activity,
                        product?.goodsId ?: "",
                        pay_type.toString()
                    )
                } else {
                    mPresenter?.requestWechatPayOrder(
                        product?.goodsId ?: "",
                        pay_type.toString()
                    )
                }

            }

        })
        UserDataUtils.updateUserInfo(this)
        mPresenter?.appInfo()
        mPresenter?.getPriceList("recharge")
        mDialog?.setCanceledOnTouchOutside(true)
        mDialog?.setCancelable(true)
        mDialog?.show()
    }

    fun dismiss() {
        mDialog?.dismiss()
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
    }


    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {
        mAdapter = StarCoinPayAdapter(this)
        val gridLayoutManager: GridLayoutManager = object : GridLayoutManager(mContext, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }

        id_activity_coin_list?.layoutManager = gridLayoutManager
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                if (TextUtils.equals(data[0].newUser, "1") && position == 0) {
                    return gridLayoutManager.spanCount
                } else {
                    return 1
                }

            }

        }
        id_activity_coin_list?.adapter = mAdapter

        mAdapter?.clear()
        mAdapter?.appendToList(data)
        if (data.size >= 3) {
            for (index in data.indices) {
                if (TextUtils.equals(data[index].select, "1")) {
                    mAdapter?.setPosition(index)
                    return
                }
            }

        }
        mAdapter?.notifyDataSetChanged()
    }

    override fun verifyOrderFail() {
        showResultLoading(false)
    }

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

    override fun verifyOrderSuc(orsder: String) {
        Utils.showToast(mContext, "充值成功")
        EventUtils.onEvent("CoinRechargeSuc", "星币充值成功")
        //  RxBus.get().post(Constant.finish_activity, 1)
        UserDataUtils.updateUserInfo(this)
        showResultLoading(true)
    }

    override fun setCanInvest(boolean: Boolean?) {

    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null) {
            if (result.pay_ali?.equals("0") == true) {
                id_rl_zfb_pay?.visibility = View.GONE
            } else {
                id_rl_zfb_pay?.visibility = View.VISIBLE
                pay_type = StarCoinPayActivity.ALI_PAY
                id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
                id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)

            }
            if (result.pay_wx?.equals("0") == true) {
                id_rl_wechat_pay?.visibility = View.GONE
            } else {
                id_rl_wechat_pay?.visibility = View.VISIBLE

            }
        }
    }

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

    override fun onResult(code: Int, result: String?) {
        val user = SettingPreference.getUserInfoData()
        id_tv_my_coin_num?.text = "星币余额：${user.starBalance}"
    }

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)
            mPresenter?.getPriceList("recharge")
        } else {
            mLoading?.setResult(false, "支付失败", 1000)
        }

    }


}