package com.zxbw.modulemain.activity

import android.os.Handler
import android.text.Html
import android.util.Log
import android.view.View
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.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.qy.JgqQyEntity
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.net.model.video.MemberEntity
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.pay.PayPresenter
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.MainLooper
import com.zxhl.cms.utils.OnRecycleItemClickListener
import com.zxhl.cms.utils.RxBus
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_login.*
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  //敏付
    }

    private var pay_type: Int? = ALI_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> { })
    }

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

    override fun requestOrderSuc(result: AliPayEntity) {
        AlipayServer.payV2(this, result.wakeup!!)
    }

    override fun requestOrderFail(errorMsg: String) {
        mLoading?.setResult(false, "请求失败", 1000)
    }

    override fun verifyOrderSuc(order: String) {
        mLoading?.setResult(true, "支付成功", 1000)
    }

    override fun verifyOrderFail(errorMsg: String) {
        mLoading?.setResult(false, "支付失败", 1000)
    }

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