package com.zxbw.modulemain.activity

import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.text.Html
import android.util.Log
import android.view.View
import android.webkit.*
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.zxbw.modulemain.R
import com.zxbw.modulemain.adapter.RightsDetailListAdapter
import com.zxbw.modulemain.contract.RightsDetailContract
import com.zxbw.modulemain.contract.RightsPayContract
import com.zxbw.modulemain.presenter.RightsDetailPresenter
import com.zxbw.modulemain.presenter.RightsPayPresenter
import com.zxhl.cms.AppContext
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.qy.RightsDetailEntity
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.pay.PayActivity
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.*
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_layout_rights_detail.*
import kotlinx.android.synthetic.main.activity_layout_rights_detail.id_img_back
import me.jessyan.autosize.utils.ScreenUtils
import java.text.DecimalFormat

/**
 * @author (wangXuewei)
 * @detail :权益详情
 */
class RightsDetailActivity : BaseActivity(), RightsDetailContract.View, RightsPayContract.View,
    OnRecycleItemClickListener<RightsDetailEntity> {

    private var mPayPresenter: RightsPayPresenter? = null
    private var mPresenter: RightsDetailPresenter? = null
    private var mAdapter: RightsDetailListAdapter? = null
    private var brandName: String = "";
    private var mRightsData: RightsDetailEntity? = null
    private var mLoading: LoadingDialog? = null

    override fun layoutID(): Int {
        return R.layout.activity_layout_rights_detail
    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun init() {
        var statusBarHeight = ScreenUtils.getStatusBarHeight()
        if (statusBarHeight <= 0) {
            statusBarHeight = 40;
        }
        id_rights_detail_title_sys_bar_view.layoutParams.height = statusBarHeight
        id_img_back.setOnClickListener(this)
        id_tv_buy_right.setOnClickListener(this)

        //权益名称
        brandName = intent?.data?.getQueryParameter("brandName") ?: ""
        var brandUrl = intent?.data?.getQueryParameter("brandUrl") ?: ""
        mPresenter = RightsDetailPresenter(this)
        initPay()
        id_tv_bread_name.text = brandName
        id_tv_bread_desc.text = "${brandName}会员权益"

        Glide.with(this).load(brandUrl)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .into(id_img_bread_logo)

        var mAppConfig = SettingPreference.getConfig()
        if (mAppConfig != null) {
            id_tv_rights_instructions.text = Html.fromHtml(mAppConfig.card_desc)
        }

        mAdapter = RightsDetailListAdapter(this, this)
        id_rcl_vip_package_list.layoutManager = GridLayoutManager(this, 3)
        id_rcl_vip_package_list.adapter = mAdapter

        mPresenter?.geRightsDetail(brandName)
    }


    override fun onClick(v: View?) {
        when (v) {
            id_img_back -> {
                finish()
            }
            id_tv_buy_right -> {
                gotoBuy()
            }
        }
    }

    override fun setRightsDetail(result: List<RightsDetailEntity>) {
        mAdapter?.clear()
        mAdapter?.appendToList(result)
        mAdapter?.setSelectPos(0)
        mRightsData = result[0]
        id_tv_bread_price.text = "¥ ${mRightsData?.salePrice}"
        var oldPrice = mRightsData?.originPrice?.toFloatOrNull() ?: 0f
        var salePrice = mRightsData?.salePrice?.toFloatOrNull() ?: 0f
        val df = DecimalFormat("#0.00")
        id_tv_bread_save_price.text = "立省${df.format(oldPrice.minus(salePrice))}元"
    }

    override fun onItemClick(view: View?, position: Int, data: RightsDetailEntity?) {
        mAdapter?.setSelectPos(position)
        mRightsData = data
        id_tv_bread_price.text = "¥ ${mRightsData?.salePrice}"
        var oldPrice = mRightsData?.originPrice?.toFloatOrNull() ?: 0f
        var salePrice = mRightsData?.salePrice?.toFloatOrNull() ?: 0f
        val df = DecimalFormat("#0.00")
        id_tv_bread_save_price.text = "立省${df.format(oldPrice.minus(salePrice))}元"
    }

    private fun gotoBuy() {
        val phoneNumber = id_edt_user_phone_number.text.toString().trim { it <= ' ' }
        if (phoneNumber.isEmpty()) {
            showToast("请输入要兑换的手机号")
            return
        }
        if (phoneNumber.length < 11) {
            showToast("请检查要兑换的手机号")
            return
        }
        if (mRightsData == null) {
            showToast("请选择要购买的权益")
            return
        }
        mLoading?.setLoading("请稍后...")
        mLoading?.show()
        mPayPresenter?.requestRightsAliPay(mRightsData?.id ?: "", pay_type.toString(), phoneNumber)
    }

    private var payResultObservable: Observable<PayResultEntity>? = 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? = H5_PAY
    private fun initPay() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPayPresenter = RightsPayPresenter(this)
        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) {
                    EventUtils.onEvent("pay_page_pay_query_order", "付款成功")
                    mPayPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    //支付宝支付
                    if (obj.payType == 1) {
                        if (obj.payStatus == "6001") {
                            EventUtils.onEvent("zfb_pay_cancel")
                        } else {
                            EventUtils.onEvent("zfb_pay_error", obj.payStatus + " msg:" + obj.txt)
                        }
                    } else {
                        EventUtils.onEvent("wx_pay_error", obj.txt)
                    }
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })

        var result = SettingPreference.getConfig()
        if (result != null) {
            if (result != null && !result.pay_config_v2.isNullOrEmpty()) {
                for (i in result.pay_config_v2!!.indices) {
                    if (result?.pay_config_v2!![i].open == 1) {
                        pay_type = result?.pay_config_v2!![i].type
                        break
                    }
                }
            }
        }
    }

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

    override fun requestOrderSuc(result: AliPayEntity) {
        if (pay_type == MIN_PAY_PROGRAM) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            JumpUtils.h5Jump("https://api.minpayment.com/pay.do?sendMsg=" + result.wakeup)
        } else if (pay_type == H5_PAY) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("h5_pay_error")
                showResultLoading(false)
            } else {
                loadH5Pay(result.outTradeNo!!)
            }
        } else if (pay_type == ALI_PAY) {
            AlipayServer.payV2(this, result.wakeup!!)
        } else {
            showToast("暂不支持")
        }
    }

    override fun requestOrderFail(errorMsg: String) {
        showResultLoading(false)
    }

    override fun verifyOrderSuc(order: String) {
        showResultLoading(true)
        showToast("成功！")
        Log.d("wxw","成功")
    }

    override fun verifyOrderFail(errorMsg: String) {
        showResultLoading(false)
    }

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

    override fun onPause() {
        super.onPause()
        isPause = true
    }
    private var isPause = false
    override fun onResume() {
        super.onResume()
        Log.d("wxw","OnResume")
        if (isPause) {
            Log.d("wxw","1OnResume"+pay_type)
            if (pay_type == PayActivity.MIN_PAY_PROGRAM || pay_type == PayActivity.H5_PAY) {
                //如果是敏支付或者H5支付
                mPayPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
            } else {
                Log.d("wxw","2OnResume"+pay_type)
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }
        }
    }

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

    private fun loadH5Pay(form: String) {
//        id_rights_pay_web_view.visibility = View.VISIBLE
        Log.d("wxw", "startTime" + System.currentTimeMillis())
        val webSettings = id_rights_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_rights_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_rights_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_rights_pay_web_view.loadUrl(NetConfig.H5.WEB_URL_H5_PAY)

    }

}