package com.duben.happyplaylet.ui.activitys

import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.CompoundButton
import androidx.recyclerview.widget.GridLayoutManager
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieCompositionFactory
import com.airbnb.lottie.LottieDrawable
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.jobo.alipay.AliPay
import com.jobo.alipay.AlipayInfoImpl
import com.jobo.rxpay.RxPay
import com.jobo.rxpay.callback.IPayCallback
import com.jobo.wxpay.WXPay
import com.jobo.wxpay.WXPayInfoImpl
import com.duben.happyplaylet.BuildConfig
import com.duben.happyplaylet.R
import com.duben.happyplaylet.common.Constant
import com.duben.happyplaylet.manager.UserManager
import com.duben.happyplaylet.mvp.model.VipBean
import com.duben.happyplaylet.mvp.model.WxPayParamBean
import com.duben.happyplaylet.mvp.presenters.VipPresenter
import com.duben.happyplaylet.mvp.views.VipView
import com.duben.happyplaylet.ui.activitys.base.BaseActivity
import com.duben.happyplaylet.ui.adapter.VipAdapter
import com.duben.happyplaylet.ui.widgets.*
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.happyplaylet.utils.AppPreferencesManager
import kotlinx.android.synthetic.main.activity_vip.*
import kotlinx.android.synthetic.main.header_layout.*


/**
 * 描述：支付
 * 作者：孟崔广
 * 时间：2022/12/22 14:48
 */
class VipActivity : BaseActivity(), VipView, View.OnClickListener, VipAdapter.OnItemClickListener,
    CompoundButton.OnCheckedChangeListener {

    companion object {
        const val IS_GUIDE = "IS_GUIDE"//是否从引导页进入
        const val wxAppId = BuildConfig.WEIXIN_APP_PAY_ID
        const val WEIXIN_PAY = "WEIXIN_PAY"
        const val ALIPAY = "ALIPAY"
        const val THIRD_ID = "THIRD_ID"
        const val VEDIO_ID = "VEDIO_ID"
    }

    private var breathAnim: YoYo.YoYoString? = null
    private var payAgreementDialog: PayAgreementDialog? = null
    private var payYesDialog: PayYesDialog? = null
    private var ruleAgreementDialog: RuleAgreementDialog? = null

    private val vipPresenter by lazy { VipPresenter() }
    private lateinit var vipAdapter: VipAdapter
    private var vipList: MutableList<VipBean.ListBean>? = null
    private var isCheckAgreeFlag: Boolean = true
    private var isGuide: Boolean = false// 从启动页进入vip界面，返回时要回到首页
    private var payType = ALIPAY// 支付类型
    private var vedioId = ""
    private var thirdId = ""


    override fun getContentViewLayoutID() = R.layout.activity_vip

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.BOTTOM

    override fun isApplyKitKatTranslucency() = false

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            isGuide = it.getBoolean(IS_GUIDE, false)
            thirdId = it.getString(THIRD_ID, "")
            vedioId = it.getString(VEDIO_ID, "")
        }
    }

    override fun initViewsAndEvents() {
        vipPresenter.attachView(this)
        if (!TextUtils.isEmpty(UserManager.getInstance().userID)) {
            vipPresenter.getVipProducts(isAliPayInstalled())
        } else {
            vipPresenter.userLogin(isAliPayInstalled())
        }

        initListener()
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, R.anim.push_bottom_out)
    }


    override fun onDestroy() {
        super.onDestroy()
        breathAnim?.stop()
        vipPresenter.detachView()
    }

    override fun getVipProductSuc(data: VipBean) {
        if (!isFinishing) {
            if (data.list != null && data.list.size > 0) {
                vipList = data.list

                //设置content样式
                if (vipList != null && vipList!!.size > 0) {
                    setVipContent(vipList!![0])
                    if (data.isNeedClick) {
                        cbVipAgreement.isChecked = true
                    } else {
                        cbVipAgreement.isChecked = false
                    }
                }
                initRvView()
            }
        }
    }

    /**
     * 设置content样式
     */
    private fun setVipContent(bean: VipBean.ListBean) {
        if (bean.isAlipay && bean.isWeixin) {
            ll_vip_alipay.visibility = View.VISIBLE
            ll_vip_wx.visibility = View.VISIBLE
        } else if (bean.isAlipay && !bean.isWeixin) {
            ll_vip_alipay.visibility = View.VISIBLE
            ll_vip_wx.visibility = View.GONE
            payType = ALIPAY
            iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
            iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
        } else if (!bean.isAlipay && bean.isWeixin) {
            ll_vip_alipay.visibility = View.GONE
            ll_vip_wx.visibility = View.VISIBLE
            payType = WEIXIN_PAY
            iv_vip_wx.setImageResource(R.mipmap.ic_vip_enable_blue)
            iv_vip_alipay.setImageResource(R.mipmap.ic_vip_none)
        }


        if (!TextUtils.isEmpty(bean.remarks)) {
            tv_vip_hint.text = bean.remarks
            tv_vip_hint.visibility = View.VISIBLE
        } else {
            tv_vip_hint.visibility = View.INVISIBLE
        }

        if (!TextUtils.isEmpty(bean.buttonText)) {
            tvVipPay.text = bean.buttonText
            tvVipAgreement.text = "点击购买即表示您同意《自动续费协议》"
        } else {
            tvVipPay.text = "立即开通"
            tvVipAgreement.text = "点击购买即表示您同意《会员付费协议》"
        }
    }

    override fun getVipPayParamsSuc(payChannel: String, paramsBean: WxPayParamBean) {
        if (!isFinishing) {
            if (TextUtils.equals(payChannel, "WEIXIN")) {
                if (paramsBean.params == null) {
                    showToast("微信支付维护中")
                    return
                }

                wxPay(paramsBean)
            } else {
                if (paramsBean.params == null) {
                    showToast("支付宝支付维护中")
                    return
                }

                alipay(paramsBean)
            }
        }
    }

    override fun queryVipOrderSuc(isPay: Boolean) {
        if (isFinishing) return

        if (isPay) {
            showToast("支付成功")
            if (!UserManager.getInstance().userIsLogin()) {
                val b = Bundle()
                b.putString(MobileLoginActivity.TYPE, "vip")
                readyGoThenKill(MobileLoginActivity::class.java, b)
            } else {
                readyGoThenKill(MainActivity::class.java)
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (UserManager.getInstance().newFlag
                    && vipList != null && vipList!!.size > 0
                ) {

                    vipAdapter.setPosition(0)
                    vipAdapter.notifyDataSetChanged()
                    val vipBean = vipList!![0]
                    if (vipBean.trial == 1) {
                        ll_vip_alipay.visibility = View.VISIBLE
                        ll_vip_wx.visibility = View.GONE
                        payType = ALIPAY
                        iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                        iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
                    }
                    backPayYesDialog(vipBean)
                    return true
                }

                if (isGuide) {
                    readyGoThenKill(MainActivity::class.java)
                } else {
                    finish()
                }
            }
        }
        return true
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.ic_vip_quit -> {
                if (UserManager.getInstance().newFlag &&
                    vipList != null && vipList!!.size > 0
                ) {
                    vipAdapter.setPosition(0)
                    vipAdapter.notifyDataSetChanged()
                    val vipBean = vipList!![0]
                    if (vipBean.trial == 1) {
                        ll_vip_alipay.visibility = View.VISIBLE
                        ll_vip_wx.visibility = View.GONE
                        payType = ALIPAY
                        iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                        iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
                    }
                    backPayYesDialog(vipBean)
                } else {
                    if (isGuide) {
                        readyGoThenKill(MainActivity::class.java)
                    } else {
                        finish()
                    }
                }
            }
            R.id.tvVipPay -> {
                if (vipList != null && vipList!!.size > 0) {
                    val vipBean = vipList!![vipAdapter.getPosition()]

                    if (!isCheckAgreeFlag) {
                        vipAgreementDialog(vipBean)
                        return
                    }

                    if (vipBean.isShowCycTips) {
                        agreementPayDialog()
                    } else {
                        if (TextUtils.equals(payType, WEIXIN_PAY)) {
                            vipPresenter.getVipPayParams(
                                "WEIXIN",
                                vipBean.pid, isAliPayInstalled()
                            )
                        } else if (TextUtils.equals(payType, ALIPAY)) {
                            vipPresenter.getVipPayParams(
                                "ALIPAY",
                                vipBean.pid, isAliPayInstalled()
                            )
                        }
                    }
                } else {
                    showToast("产品未配置")
                }
            }
            R.id.tvVipAgreement -> {
                val bundle = Bundle()
                bundle.putString(WebActivity.WEB_TITLE, getString(R.string.members_name))
                bundle.putString(WebActivity.WEB_URL, Constant.MEMBERS_URL)
                readyGo(WebActivity::class.java, bundle)
            }
            R.id.ll_vip_alipay -> {
                payType = ALIPAY
                iv_vip_alipay.setImageResource(R.mipmap.ic_vip_enable_blue)
                iv_vip_wx.setImageResource(R.mipmap.ic_vip_none)
            }
            R.id.ll_vip_wx -> {
                payType = WEIXIN_PAY
                iv_vip_wx.setImageResource(R.mipmap.ic_vip_enable_blue)
                iv_vip_alipay.setImageResource(R.mipmap.ic_vip_none)
            }
        }
    }

    private fun initRvView() {
        if (vipList != null && vipList!!.size > 0) {
            val gridLayoutManager = GridLayoutManager(this, 3)
            rvVip.layoutManager = gridLayoutManager
            vipAdapter = VipAdapter(vipList!!)
            rvVip.adapter = vipAdapter
            vipAdapter.setOnItemClickListener(this)
        }
    }

    private fun initListener() {
        val lottieDrawable = LottieDrawable()
        LottieCompositionFactory.fromAsset(context, "choose_pay.json")
            .addListener { result: LottieComposition? ->
                lottieDrawable.setImagesAssetsFolder("images/")
                lottieDrawable.composition = result
                lottieDrawable.loop(true)
                lottieDrawable.playAnimation()
            }
        ic_vip_top.setImageDrawable(lottieDrawable)

        shimmer_text?.postDelayed({
            shimmer_text?.startShimmerAnimation()
            breathAnim =
                YoYo.with(Techniques.Pulse).duration(700).repeat(-1).playOn(shimmer_text)
        }, 200)

        ic_vip_quit.setOnClickListener(this)
        tvVipPay.setOnClickListener(this)
        tvVipAgreement.setOnClickListener(this)
        ll_vip_alipay.setOnClickListener(this)
        ll_vip_wx.setOnClickListener(this)
        cbVipAgreement.setOnCheckedChangeListener(this)

    }

    override fun onItemClick(position: Int) {
        vipAdapter.setPosition(position)
        vipAdapter.notifyDataSetChanged()

        //设置content样式
        if (vipList != null && vipList!!.size > 0) {
            setVipContent(vipList!![position])
        }
    }

    fun wxPay(wxParanBean: WxPayParamBean) {
        val data = wxParanBean.params
        //实例化微信支付策略
        val wxPay: WXPay = WXPay.getInstance()
        //构造微信订单实体。一般都是由服务端直接返回。
        val wxPayInfoImpl = WXPayInfoImpl()
        wxPayInfoImpl.timestamp = data.timestamp
        wxPayInfoImpl.sign = data.sign
        wxPayInfoImpl.prepayId = data.prepayid
        wxPayInfoImpl.partnerid = data.partnerid
        wxPayInfoImpl.appid = wxAppId
        wxPayInfoImpl.nonceStr = data.noncestr
        wxPayInfoImpl.packageValue = data.packageX
        //策略场景类调起支付方法开始支付，以及接收回调。
        RxPay.pay(wxPay, this, wxPayInfoImpl, object : IPayCallback {
            override fun success() {
                UserManager.getInstance().vipFlag = true
                vipPresenter?.queryVipOrder(wxParanBean.tid.toString(), true)
            }

            override fun failed(code: Int, message: String?) {
                vipPresenter?.queryVipOrder(wxParanBean.tid.toString(), false)

            }

            override fun cancel() {
                vipPresenter?.queryVipOrder(wxParanBean.tid.toString(), false)

            }
        })
    }

    fun alipay(wxParanBean: WxPayParamBean) {
        try {
            // 自动签约付费
            if (wxParanBean.params.isSign) {
                openAutoAlipay(wxParanBean.params.params)
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }


        //实例化支付宝支付策略
        val aliPay = AliPay()
        //构造支付宝订单实体。一般都是由服务端直接返回。
        val alipayInfoImpl = AlipayInfoImpl()
        alipayInfoImpl.setOrderInfo(wxParanBean.params.params)
        //策略场景类调起支付方法开始支付，以及接收回调。
        RxPay.pay(aliPay, this, alipayInfoImpl, object : IPayCallback {
            override fun success() {
                UserManager.getInstance().vipFlag = true
                vipPresenter?.queryVipOrder(wxParanBean.tid.toString(), true)
            }

            override fun failed(code: Int, message: String?) {
                vipPresenter?.payError(code)
                if (!TextUtils.isEmpty(message)) {
                    showToast(message)
                }
            }

            override fun cancel() {
                vipPresenter?.queryVipOrder(wxParanBean.tid.toString(), false)

            }
        })
    }

    /**
     * 检测是否安装支付宝
     *
     * true-安装支付宝
     */
    fun isAliPayInstalled(): Boolean {
        try {
            val uri: Uri = Uri.parse("alipays://platformapi/startApp")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName = intent.resolveActivity(context.getPackageManager())
            return componentName != null
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    /**
     * 自动续费
     */
    fun openAutoAlipay(url: String) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        startActivity(intent)
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        isCheckAgreeFlag = isChecked
    }

    /**
     * 返回支付弹窗-签约
     */
    private fun backPayYesDialog(vipBean: VipBean.ListBean) {
        payYesDialog = PayYesDialog(context, vipBean, object : DialogListener() {
            override fun onClick(v: View) {
                if (!isFinishing() && payYesDialog != null && payYesDialog!!.isShowing()) {
                    payYesDialog!!.dismiss()
                }
                when (v.id) {
                    R.id.iv_dialog_vip_quit -> {
                        if (isGuide) {
                            readyGoThenKill(MainActivity::class.java)
                        } else {
                            finish()
                        }
                    }
                    R.id.tv_dialog_vip_next -> {
                        cbVipAgreement.isChecked = true

                        if (vipList != null && vipList!!.size > 0) {
                            val vipBean = vipList!![vipAdapter.getPosition()]
                            if (TextUtils.equals(payType, WEIXIN_PAY)) {
                                vipPresenter.getVipPayParams(
                                    "WEIXIN",
                                    vipBean.pid, isAliPayInstalled()
                                )
                            } else if (TextUtils.equals(payType, ALIPAY)) {
                                vipPresenter.getVipPayParams(
                                    "ALIPAY",
                                    vipBean.pid, isAliPayInstalled()
                                )
                            }
                        } else {
                            showToast("产品未配置")
                        }
                    }
                }
            }
        })
        payYesDialog!!.show()
    }

    /**
     * 自动续费协议弹窗-支付宝
     */
    private fun agreementPayDialog() {
        payAgreementDialog = PayAgreementDialog(context, object : DialogListener() {
            override fun onClick(v: View) {
                if (!isFinishing() && payAgreementDialog != null && payAgreementDialog!!.isShowing()) {
                    payAgreementDialog!!.dismiss()
                }
                when (v.id) {
                    R.id.tv_agreement_next -> {
                        ruleAgreementPayDialog()
                    }
                }
            }
        })
        payAgreementDialog!!.show()
    }

    /**
     * 试用订阅规则说明-仿支付宝
     */
    private fun ruleAgreementPayDialog() {
        if (vipList != null && vipList!!.size > 0) {
            val vipBean = vipList!![vipAdapter.getPosition()]
            ruleAgreementDialog = RuleAgreementDialog(context, object : DialogListener() {
                override fun onClick(v: View) {
                    if (!isFinishing() && ruleAgreementDialog != null && ruleAgreementDialog!!.isShowing()) {
                        ruleAgreementDialog!!.dismiss()
                    }
                    when (v.id) {
                        R.id.tv_agreement_next -> {
                            if (TextUtils.equals(payType, WEIXIN_PAY)) {
                                vipPresenter.getVipPayParams(
                                    "WEIXIN",
                                    vipBean.pid, isAliPayInstalled()
                                )
                            } else if (TextUtils.equals(payType, ALIPAY)) {
                                vipPresenter.getVipPayParams(
                                    "ALIPAY",
                                    vipBean.pid, isAliPayInstalled()
                                )
                            }

                        }
                    }
                }
            })
            ruleAgreementDialog!!.setText(
                vipBean.remarks,
                vipBean.trialFirstDay,
                vipBean.price,
                vipBean.title
            )
            ruleAgreementDialog!!.show()
        } else {
            showToast("产品未配置")
        }
    }

    /**
     * 未勾选协议弹窗
     */
    private fun vipAgreementDialog(bean: VipBean.ListBean) {
        var agreeStr = "会员付费协议"
        if (bean.isShowCycTips) {
            agreeStr = "自动续费协议"
        }
        val cdaa = CustomDialogAgreement(context, object : DialogListener() {
            override fun onClick(dialog: Dialog?, v: View?) {
                dialog?.dismiss()
                when (v?.id) {
                    R.id.dialog_btn_right -> {
                        cbVipAgreement.isChecked = true


                        if (vipList != null && vipList!!.size > 0) {
                            val vipBean = vipList!![vipAdapter.getPosition()]
                            if (vipBean.isShowCycTips) {
                                agreementPayDialog()
                            } else {
                                if (TextUtils.equals(payType, WEIXIN_PAY)) {
                                    vipPresenter.getVipPayParams(
                                        "WEIXIN",
                                        vipBean.pid, isAliPayInstalled()
                                    )
                                } else if (TextUtils.equals(payType, ALIPAY)) {
                                    vipPresenter.getVipPayParams(
                                        "ALIPAY",
                                        vipBean.pid, isAliPayInstalled()
                                    )
                                }
                            }
                        } else {
                            showToast("产品未配置")
                        }
                    }
                }
            }
        })
        cdaa.setTitle(agreeStr)
        cdaa.setContent(agreeStr)
        cdaa.setLeft("不同意")
        cdaa.setLeftColor(R.color.gray)
        cdaa.setRight("同意")
        cdaa.setRightColor(R.color.main_mints)
        cdaa.show()
    }
}