package com.duben.microtribe.ui.activitys

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import com.jobo.alipay.AliPay
import com.jobo.alipay.AlipayInfoImpl
import com.jobo.rxpay.RxPay
import com.jobo.rxpay.callback.IPayCallback
import com.duben.microtribe.R
import com.duben.microtribe.manager.ActivityPageManager
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.mvp.model.WxPayParamBean
import com.duben.microtribe.mvp.presenters.NinePayPresenter
import com.duben.microtribe.mvp.views.NinePayView
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.library.utils.nodoubleclick.AntiShake
import kotlinx.android.synthetic.main.activity_nine_pay.*

/**
 * 抽奖弹窗
 */
class NinePayActivity : BaseActivity(), View.OnClickListener, NinePayView {

    companion object {
        const val PID = "PID"
        const val TITLE = "TITLE"
        const val TYPE = "TYPE"
    }

    private val ninePayPresenter by lazy { NinePayPresenter() }

    private var pid = ""
    private var title = ""
    private var type = ""

    override fun isApplyKitKatTranslucency() = false

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.SCALE

    override fun getContentViewLayoutID() = R.layout.activity_nine_pay

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            pid = it.getString(PID, "")
            title = it.getString(TITLE, "")
            type = it.getString(TYPE, "")
        }
    }

    override fun initViewsAndEvents() {
        ninePayPresenter.attachView(this)
        initListener()
        tv_nine_pay_title.text = title
        when (type) {
            "o" ->// 一年
                iv_nine_pay_type.setImageResource(R.mipmap.ic_nine_year)
            "f" ->// 终身
                iv_nine_pay_type.setImageResource(R.mipmap.ic_nine_all)
            "m" -> // 手机
                iv_nine_pay_type.setImageResource(R.mipmap.ic_nine_mobile)
            else ->// 支付
                iv_nine_pay_type.setImageResource(R.mipmap.ic_nine_vip)
        }
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, R.anim.scale_out)
    }

    override fun onDestroy() {
        super.onDestroy()
        ninePayPresenter.detachView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(
            keyCode,
            event
        )
    }

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

        when (v?.id) {
            R.id.iv_nine_left_next -> finish()
            R.id.iv_nine_right_next -> ninePayPresenter.getVipPayParams(pid)
        }
    }

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

            alipay(paramsBean)
        }
    }

    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
                ninePayPresenter?.queryVipOrder(wxParanBean.tid.toString(), true)
            }

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

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

            }
        })
    }

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

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

        if (isPay) {
            showToast("支付成功")
            Handler(Looper.getMainLooper()).postDelayed({
                readyGo(MainActivity::class.java)
                val activity =
                    ActivityPageManager.getInstance().getActivity(MainActivity::class.java)
                if (activity != null && activity is MainActivity) {
                    activity.clickTab4Layout()
                }
            }, 500)
        } else {
            finish()
        }
    }

    private fun initListener() {
        iv_nine_left_next.setOnClickListener(this)
        iv_nine_right_next.setOnClickListener(this)
    }
}
