package com.zxhl.cms.pay


import android.text.TextUtils
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.zxhl.cms.R
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.box.AppInEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.EventUtils.onEvent
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.cms.widget.RecyclerViewSpacesItemDecoration
import com.zxhl.novel.utils.server.PayResultEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_member.*
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.*

/**
 * Created by gaoleichao on 2021/8/30
 */
class PayActivity : BaseActivity(), PayContract.View,
    OnRecycleItemClickListener<MemberEntity.ProductDetail>, AdCallback<String> {
    override fun onClick(p0: View?) {

    }

    override fun layoutID(): Int = R.layout.activity_member

    private var mPresenter: PayContract.Presenter? = null
    private var mAdapter: PayAdapter? = null
    private var mLoading: LoadingDialog? = null

    private var payResultObservable: Observable<PayResultEntity>? = null

    companion object {
        const val ALI_PAY = 1   //支付宝支付类型
        const val WECHAT_PAY = 2  //微信支付类型
        const val MINI_PROGRAM = 11  //微信支付类型
    }

    private var pay_type = 1
    override fun before() {
        super.before()
        setStatusBarBackground(resources.getColor(R.color.transparent))
    }


    override fun init() {

        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        id_img_back?.setOnClickListener {
            finish()
        }
        id_img_member_record?.setOnClickListener {
            JumpUtils.memberRecordJump()
        }
        id_rl_wechat_pay?.setOnClickListener {
            pay_type = 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 = ALI_PAY
            id_img_wechat?.setImageResource(R.drawable.icon_xuanzhong_default)
            id_img_ali?.setImageResource(R.drawable.icon_xuanzhong)

        }
        id_tv_pay_service?.setOnClickListener {
            JumpUtils.webJump("充值服务协议",NetConfig.H5.WEB_URL_BUYER_KNOW)
        }
        EventUtils.onEvent("pay_page_show", "会员权益页")

        mPresenter = PayPresenter(this)
        mAdapter = PayAdapter(this)
        val widthScreen = windowManager?.defaultDisplay?.width
        val widthDecoration = (widthScreen!! - Utils.dip2px(20 * 4) - Utils.dip2px(100 * 3)) / 6
        val gridLayoutManager: GridLayoutManager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        id_activity_member_list?.layoutManager = gridLayoutManager
        val stringIntegerHashMap: HashMap<String, Int> = HashMap()
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.TOP_DECORATION] =
            Utils.dip2px(10) //top间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION] =
            Utils.dip2px(10) //底部间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.LEFT_DECORATION] =
            Utils.dip2px(5)//左间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.RIGHT_DECORATION] =
            Utils.dip2px(5) //右间距
        id_activity_member_list?.addItemDecoration(
            RecyclerViewSpacesItemDecoration(
                stringIntegerHashMap
            )
        )
        id_activity_member_list?.adapter = mAdapter
        id_tv_pay_tex?.setOnClickListener {
            if (pay_type == 0) {
                Utils.showToast(this, "请选择支付类型")
                return@setOnClickListener
            }
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            EventUtils.onEvent("VIPRecharge", "点击VIP充值")
            if (pay_type == 1) {
                mPresenter?.requestAliPay(
                    this,
                    product?.goodsId?:"",
                    pay_type.toString()
                )
            } else {
                mPresenter?.requestWechatPayOrder(
                    product?.goodsId?:"",
                    pay_type.toString()
                )
            }
        }
        id_ll_pay_bottom?.setOnClickListener {
            if (pay_type == 0) {
                Utils.showToast(this, "请选择支付类型")
                return@setOnClickListener
            }
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            EventUtils.onEvent("VIPRechargeClick", "VIP充值")
                if (pay_type == 1) {
                    mPresenter?.requestAliPay(
                        this,
                        product?.goodsId?:"",
                        pay_type.toString()
                    )
                } else {
                    mPresenter?.requestWechatPayOrder(
                        product?.goodsId?:"",
                        pay_type.toString()
                    )
                }

        }

        payResultObservable = RxBus.get().register(Constant.PAY_RESULT, PayResultEntity::class.java)
        payResultObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<PayResultEntity> { obj ->
                Log.d("qqbs", "verifyPay:${obj.txt}")
                println("verifyPay payResultObservable------------------------------- order:${obj.txt}")
                if (obj.isPaySuc) {
                    onEvent("pay_success", "付款成功")
                    mPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })

        id_activity_member_pri?.setOnClickListener {
            JumpUtils.webJump(R.string.PrivacyAgreement.toString(), NetConfig.H5.WEB_URL_PRIVACY)
        }

        id_activity_member_user?.setOnClickListener {
            JumpUtils.webJump(R.string.UserAgreement.toString(), NetConfig.H5.WEB_URL_USER)
        }

        EventUtils.onEvent("member_page_show")
    }

    override fun data() {
        super.data()
        UserDataUtils.updateUserInfo(this)
        mPresenter?.appInfo()
        mPresenter?.getPriceList("vip")

    }


    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {
        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()
    }


    private var product: MemberEntity.ProductDetail? = null


    override fun onItemClick(view: View?, position: Int, data: MemberEntity.ProductDetail?) {
        this.product = data
        EventUtils.onEvent("member_page_item_click", data?.cash + "")
    }

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

    }



    override fun verifyOrderFail() {
        showResultLoading(false)
    }

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

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

    override fun setCanInvest(boolean: Boolean?) {
        if (boolean == true) {

        } else {
            Utils.showToast(this, "充值上限，无法充值")
        }
    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null) {
            if (result?.pay_ali.equals("0")) {
                id_rl_zfb_pay.visibility = View.GONE
            } else {
                id_rl_zfb_pay.visibility = View.VISIBLE
                pay_type = 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")) {
                id_rl_wechat_pay.visibility = View.GONE
            } else {
                id_rl_wechat_pay.visibility = View.VISIBLE

            }
        }
    }

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

    override fun onResume() {
        super.onResume()
        if (mLoading != null) {
            mLoading?.dismiss()
        }
//        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
//        MobclickAgent.onPause(this)
    }


    override fun onResult(code: Int, result: String?) {
        Log.e("MXL","支付完成刷新数据")
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        id_tv_nick_name?.text = user.nickname
        if (!TextUtils.isEmpty(user.headImage)) {
            Glide.with(this).load(user.headImage)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(id_img_head)
        } else {
            id_img_head.setImageResource(R.drawable.icon_user_photo_default)
        }
        if (user.memberType==1) {
            id_tv_my_time?.text = "会员有效期：${user.memberEndTime}"
            id_tv_my_time?.visibility = View.VISIBLE
            id_my_vip?.visibility=View.VISIBLE
            id_tv_pay_tex?.text="立即续费"
            id_tv_kaitong?.text="立即续费"
        } else {
            id_tv_my_time?.visibility = View.GONE
            id_my_vip?.visibility=View.GONE
            id_tv_pay_tex?.text="立即开通"
            id_tv_kaitong?.text="立即开通"
        }
    }

}