package com.zxbw.modulemain.activity

import android.content.Intent
import android.graphics.Paint
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.pay.paytypelibrary.base.OnPayResultListener
import com.pay.paytypelibrary.base.OrderInfo
import com.pay.paytypelibrary.base.PayUtil
import com.zx.ad.AdManager
import com.zx.ad.callback.InterertionAdListener
import com.zxbw.modulemain.R
import com.zxbw.modulemain.adapter.OperatorAdapter
import com.zxbw.modulemain.adapter.RechargeAdapter
import com.zxbw.modulemain.contract.RechargeContract
import com.zxbw.modulemain.presenter.RechargePresenter
import com.zxbw.modulemain.view.DialogUtils
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.box.MobileOpEntity
import com.zxhl.cms.net.model.qy.CouponsEntity
import com.zxhl.cms.net.model.uc.AliPayEntity
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.net.model.uc.WeChatPayEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.H5PayUtil
import com.zxhl.cms.pay.PaymentConfig
import com.zxhl.cms.pay.PaymentFunAdapter
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_recharge.*
import kotlinx.android.synthetic.main.activity_layout_recharge.id_img_back
import kotlinx.android.synthetic.main.activity_layout_recharge.id_rights_pay_web_view
import kotlinx.android.synthetic.main.activity_layout_recharge.id_rl_h5_pay_view

//话费充值页面
class XymhRechargeActivity : BaseActivity(), OnRecycleItemClickListener<MemberEntity.ProductDetail>,
    RechargeContract.View {
    private var mPayFunAdapter: PaymentFunAdapter? = null;
    private var mAdapter: RechargeAdapter? = null
    private var mOperatorAdapter: OperatorAdapter? = null
    private var mPresenter: RechargePresenter? = null
    private var couponsentity: CouponsEntity? = null
    private var mLoading: LoadingDialog? = null
    private var pay_type: Int? = PaymentConfig.H5_PAY
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var mobileOp: String? = ""
    private var selectPrice: String? = ""
    var goodsID: String? = ""
    var couponId: String? = ""
    private var position: Int? = -1
    override fun onClick(v: View?) {
        when (v) {
            id_tv_select_coupons -> {
                //如果有默认选中，传入默认选中的优惠券
                DialogUtils.showFetchAllCard(
                    this,
                    selectPrice.toString(),
                    couponsentity,
                    mCouponsResult,
                    object : DialogUtils.OnFetchCardListener {
                        override fun onSelectCoupons(coupons: CouponsEntity?) {
                            //coupons==null  没有选择优惠券  !=null  选中的优惠券信息
                            couponsentity = coupons
                            setCouponInfo(couponsentity)
                        }
                    })
            }
        }
    }

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

    override fun layoutID(): Int {
        return R.layout.activity_layout_recharge
    }
    fun showIntriAd(){
        AdManager.loadInterAd(this!!, object : InterertionAdListener {
            override fun onAdShow() {

            }

            override fun onAdError(errorMsg: String?) {
                Log.e("MXL","onAdError"+errorMsg)
            }

            override fun onAdClose() {

            }

        })
    }
    override fun init() {
        showIntriAd()
        id_img_back?.setOnClickListener {
            finish()
        }
        val user = SettingPreference.getUserInfoData()
        initPay()
        mOperatorAdapter = OperatorAdapter(
            this,
            OnRecycleItemClickListener<MobileOpEntity> { view, position, data ->
                mobileOp = data.value

            })
        id_rl_yunyingshang?.layoutManager = GridLayoutManager(this, 3)
        id_rl_yunyingshang?.adapter = mOperatorAdapter
        var result = SettingPreference.getConfig()
        if (!result?.mobileOpList.isNullOrEmpty()) {
            mOperatorAdapter?.clear()
            mOperatorAdapter?.appendToList(result?.mobileOpList)
            mOperatorAdapter?.notifyDataSetChanged()
        }

        mPresenter = RechargePresenter(this)
        mAdapter = RechargeAdapter(this, this)
//        id_rl_recharge?.layoutManager = GridLayoutManager(this, 3)
        id_rl_recharge?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        id_rl_recharge?.adapter = mAdapter
        mPresenter?.getFetchCard()
//        mPresenter?.getPayList("mobileFee")
        id_edit_user_phone?.setText(user.nickname.toString())
        id_edit_user_phone?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(s!!.length>=11){
                    getMobileop(s.toString())
                }else{
                    mobileOp = ""
                    mOperatorAdapter?.setPosition(-1)
                }


            }

            override fun afterTextChanged(s: Editable?) {


            }

        })
        getMobileop("13126735008")
        id_tv_select_coupons?.setOnClickListener(this)
        id_tv_chongzhi?.setOnClickListener {
            topay()
        }
    }

    fun getMobileop(mobile: String) {
        if (TextUtils.isEmpty(mobile) || mobile.trim().length != 11) {
            return
        }
        if (mobile.trim().substring(0, 3).equals("134")
            || mobile.trim().substring(0, 3).equals("135")
            || mobile.trim().substring(0, 3).equals("136")
            || mobile.trim().substring(0, 3).equals("137")
            || mobile.trim().substring(0, 3).equals("138")
            || mobile.trim().substring(0, 3).equals("139")
            || mobile.trim().substring(0, 3).equals("147")
            || mobile.trim().substring(0, 3).equals("150")
            || mobile.trim().substring(0, 3).equals("151")
            || mobile.trim().substring(0, 3).equals("152")
            || mobile.trim().substring(0, 3).equals("157")
            || mobile.trim().substring(0, 3).equals("158")
            || mobile.trim().substring(0, 3).equals("159")
            || mobile.trim().substring(0, 3).equals("178")
            || mobile.trim().substring(0, 3).equals("182")
            || mobile.trim().substring(0, 3).equals("183")
            || mobile.trim().substring(0, 3).equals("184")
            || mobile.trim().substring(0, 3).equals("187")
            || mobile.trim().substring(0, 3).equals("188")

        ) {
            mobileOp = "SHKC_MC"
            mOperatorAdapter?.setPosition(0)
        } else if (mobile.trim().substring(0, 3).equals("130")
            || mobile.trim().substring(0, 3).equals("131")
            || mobile.trim().substring(0, 3).equals("132")
            || mobile.trim().substring(0, 3).equals("145")
            || mobile.trim().substring(0, 3).equals("155")
            || mobile.trim().substring(0, 3).equals("156")
            || mobile.trim().substring(0, 3).equals("175")
            || mobile.trim().substring(0, 3).equals("176")
            || mobile.trim().substring(0, 3).equals("185")
            || mobile.trim().substring(0, 3).equals("186")
        ) {
            mOperatorAdapter?.setPosition(1)
            mobileOp = "SHKC_CU_MC"
        } else if (mobile.trim().substring(0, 3).equals("133")
            || mobile.trim().substring(0, 3).equals("149")
            || mobile.trim().substring(0, 3).equals("153")
            || mobile.trim().substring(0, 3).equals("177")
            || mobile.trim().substring(0, 3).equals("180")
            || mobile.trim().substring(0, 3).equals("181")
            || mobile.trim().substring(0, 3).equals("189")
        ) {
            mobileOp = "SHKC_CT_MC"
            mOperatorAdapter?.setPosition(2)
            Log.e("MXL", "电信号")
        } else {
            mobileOp = ""
            mOperatorAdapter?.setPosition(-1)
            Log.e("MXL", "未知")
        }

    }

    fun initPay() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        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", "付款成功")
                    mPresenter?.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> { })

        mPayFunAdapter = PaymentFunAdapter(
            this
        ) { view, position, data ->
            pay_type = data.type
            mPayFunAdapter?.setPosition(position)
        }
        id_rcl_payment_list.layoutManager = LinearLayoutManager(this)
        id_rcl_payment_list.adapter = mPayFunAdapter
        var result = SettingPreference.getConfig()
        if (result != null) {
            if (!result.pay_config_v2.isNullOrEmpty()) {
                mPayFunAdapter?.clear()
                mPayFunAdapter?.appendToList(result.pay_config_v2)
                for (i in result.pay_config_v2!!.indices) {
                    if (result?.pay_config_v2!![i].open == 1) {
                        pay_type = result?.pay_config_v2!![i].type
                        mPayFunAdapter?.setPosition(i)
                        break
                    }
                }
            }
            if (result.recharge_desc.isNullOrEmpty()) {
                id_tv_recharge_desc.visibility = View.GONE
            } else {
                id_tv_recharge_desc.text = result.recharge_desc
                id_tv_recharge_desc.visibility = View.VISIBLE
            }
        }
    }

    private var mHandler: Handler = Handler {
        when (it.what) {
            0 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "取消支付", 1000)
                }
            }
            1 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "支付异常", 0)
                }
                id_rl_h5_pay_view.visibility = View.VISIBLE
                EventUtils.onEvent("h5_pay_end")
            }
            2 -> {
                if (mLoading != null) {
                    mLoading?.setResult(false, "支付异常", 0)
                }
                id_rl_h5_pay_view.visibility = View.VISIBLE
            }
        }
        false
    }

    fun topay() {
        val phoneNumber = id_edit_user_phone.text.toString().trim { it <= ' ' }
        if (phoneNumber.isEmpty()) {
            showToast("请输入要兑换的手机号")
            return
        }
        if (phoneNumber.length != 11) {
            showToast("请检查要兑换的手机号")
            return
        }
        if (TextUtils.isEmpty(mobileOp)) {
            showToast("请选择运营商")
            return
        }
        DialogUtils.showRechargeTips(this, phoneNumber) {
            isClickPayBtn = true
            mLoading?.setLoading("请稍后...")
            mLoading?.show()
            Log.e("MXL", "s" + pay_type)
            if (pay_type == 2) {
                mPresenter?.requestWechatPayOrder(
                    "xxsqshop://recharge",
                    goodsID.toString(),
                    pay_type.toString(),
                    phoneNumber,
                    "8080",
                    false,
                    "",
                    couponsentity?.id,
                    mobileOp
                )
            } else {
                mPresenter?.requestRightsAliPay(
                    "xxsqshop://recharge",
                    goodsID.toString(),
                    pay_type.toString(),
                    phoneNumber,
                    "8080",
                    false,
                    "",
                    couponsentity?.id,
                    mobileOp
                )
            }


        }

    }

    private var mCouponsResult: List<CouponsEntity>? = null
    override fun setCouponsList(result: List<CouponsEntity>?) {
        mCouponsResult = result
//        if (!result.isNullOrEmpty()) {
//            couponsentity = result.get(0)
//            setCouponInfo(couponsentity)
//        }
    }

    override fun requestOrderSuc(result: AliPayEntity) {
        Log.e("MXL", "pay_type" + pay_type)
        if (pay_type == PaymentConfig.MIN_PAY_PROGRAM) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            JumpUtils.h5Jump("https://api.minpayment.com/pay.do?sendMsg=" + result.wakeup)
        } else if (pay_type == PaymentConfig.H5_PAY) {
            SettingPreference.setOutTradeNo(result?.outTradeNo)
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("h5_pay_error")
                showResultLoading(false)
            } else {
                mHandler.sendEmptyMessageDelayed(1, 8000)
                H5PayUtil().loadH5PayWeb(
                    this,
                    id_rights_pay_web_view,
                    result.outTradeNo ?: "",
                    object : H5PayUtil.H5PayCallBack {
                        override fun jumpZfbAppSuc() {
                            id_rl_h5_pay_view.visibility = View.GONE
                            EventUtils.onEvent("h5_open_zfb_suc")
                            mHandler.removeMessages(1)
                        }

                        override fun jumpZfbAppException(e: Exception) {
                            EventUtils.onEvent("h5_open_zfb_error", e.toString())
                            mHandler.removeMessages(1)
                            mHandler.sendEmptyMessage(2)
                        }

                        override fun loadH5Error1(errorStr: String) {
                            EventUtils.onEvent("h5_pay_error1", errorStr)
                        }

                        override fun loadH5Error2(errorStr: String) {
                            EventUtils.onEvent("h5_pay_error2", errorStr)
                        }
                    })
            }
        } else if (pay_type == PaymentConfig.ALI_PAY) {
            AlipayServer.payV2(this, result.wakeup!!)
        } else if (pay_type == PaymentConfig.SD_PAY) {
            SettingPreference.setOutTradeNo(result.outTradeNo)
            PayUtil.CashierPaySingle(this, result.wakeup, object : OnPayResultListener {
                override fun onSuccess(p0: OrderInfo?) {

                }

                override fun onError(p0: String?) {
                    EventUtils.onEvent("SdPayError", "error:${p0}")
                    mLoading?.setResult(false, "支付异常", 1000)
                }
            });
        } else if (pay_type == PaymentConfig.ZFB_H5_PAY || pay_type == PaymentConfig.WX_H5_PAY || pay_type == PaymentConfig.HUI_FU_H5_PAY1 || pay_type == PaymentConfig.HUI_FU_H5_PAY2) {
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("h5_pay_error")
                showResultLoading(false)
            } else {
                SettingPreference.setOutTradeNo(result.outTradeNo)
                H5PayUtil().loadH5AppPay(
                    this,
                    pay_type!!,
                    result.wakeup ?: "",
                    object : H5PayUtil.H5AppPayCallBack {
                        override fun jumpAppException(e: Exception) {
                            EventUtils.onEvent("H5AppPayError", "error:${pay_type}")
                            if (pay_type == PaymentConfig.ZFB_H5_PAY || pay_type == PaymentConfig.HUI_FU_H5_PAY1) {
                                mLoading?.setResult(false, "支付失败,请安装支付宝后重试", 1000)
                            } else {
                                mLoading?.setResult(false, "支付失败,请安装微信后重试", 1000)
                            }
                        }
                    })
            }
        } else if (pay_type == PaymentConfig.WECHAT_PAY) {
            if (result.outTradeNo.isNullOrEmpty()) {
                EventUtils.onEvent("wechat_pay_error")
                showResultLoading(false)
            } else {

            }
        } else {
            showToast("暂不支持")
            EventUtils.onEvent("payment_error", "$pay_type")
        }
    }

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

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val data = intent?.data
        if (data != null) {
            if (pay_type == PaymentConfig.SD_PAY) {
                val payCode = data.getQueryParameter("payCode")
                if (payCode == "2") {
                    isPause = false
                    mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
                } else {
                    showResultLoading(false)
                }
            }
        }
    }

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

    override fun verifyOrderSuc(order: String) {
        isClickPayBtn = false
        SettingPreference.setOutTradeNo("")
        showResultLoading(true)
        finish()
        JumpUtils.PaySuceessJump("2")
    }

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

    override fun setAppInfo(result: AppInEntity?) {

    }

    override fun setPayList(result: MemberEntity) {
        for (i in result?.goodsList!!) {
            if (i.originalPrice.equals("50")) {

            }
        }
        mAdapter?.clear()
        mAdapter?.appendToList(result?.goodsList)
        mAdapter?.notifyDataSetChanged()
        if (!result.goodsList.isNullOrEmpty()) {
            if (result.goodsList!!.size >= 0) {
                useCoupn(0, 0)
            }
        }

    }

    fun useCoupn(default: Int, price: Int) {
        if (!mCouponsResult.isNullOrEmpty()) {
            for (i in mCouponsResult!!) {
                if (price == 200) {
                    if (TextUtils.equals(i.amount, "10.0")) {
                        //判断当有5元券时 帮他选择100元档位且使用当前5元的券
                        Log.e("MXL", "优先使用10元优惠券")
                        couponsentity = i
                        setCouponInfo(couponsentity)
                        break
                    }
                } else {
                    if (TextUtils.equals(i.amount, "5.0")) {
                        //判断当有5元券时 帮他选择100元档位且使用当前5元的券
                        Log.e("MXL", "使用5元优惠券")
                        if (default == 0) {
                            mAdapter?.setPosition(1)
                            selectPrice = mAdapter?.getItem(1)?.originalPrice
                            goodsID = mAdapter?.getItem(1)?.goodsId
                            memberentity = mAdapter?.getItem(1)
                        }
                        couponsentity = i
                        setCouponInfo(couponsentity)
                        break
                    }
                }

            }
            Log.e("MXL", "循环结束取到优惠券信息")
            if (couponsentity == null) {
                Log.e("MXL", "没有5元的 使用10元券")
                if (default == 0) {
                    mAdapter?.setPosition(2)
                    selectPrice = mAdapter?.getItem(2)?.originalPrice
                    goodsID = mAdapter?.getItem(2)?.goodsId
                    memberentity = mAdapter?.getItem(2)
                }
                couponsentity = mCouponsResult!!.get(0)

                setCouponInfo(couponsentity)
            }
            Log.e("MXL", "price:" + price + "default:" + default)

            //    mAdapter?.updateData( couponsentity?.amount.toString())
            if (SettingPreference.getShowUseDiscount().equals("0")) {
                DialogUtils.showHuafeiTips(this)
            }

        } else {
            Log.e("MXL", "当前无可用优惠券")
            mAdapter?.updateData("")
            if (default == 0) {
                memberentity = mAdapter?.getItem(1)
                mAdapter?.setPosition(1)
                selectPrice = mAdapter?.getItem(1)?.originalPrice
                goodsID = mAdapter?.getItem(1)?.goodsId
            }
            couponsentity = null
            setCouponInfo(couponsentity)


        }
    }

    var memberentity: MemberEntity.ProductDetail? = null
    override fun onItemClick(view: View?, position: Int, data: MemberEntity.ProductDetail?) {
        memberentity = data
        selectPrice = data?.originalPrice
        goodsID = data?.goodsId
        chosseData(position, data)
    }

    fun chosseData(position: Int, data: MemberEntity.ProductDetail?) {
        when (position) {
            0 -> {
                Log.e("MXL", "选0")
                couponsentity = null
                setCouponInfo(couponsentity)
                setBootomPrice(data)
                return
            }
            1 -> {
                Log.e("MXL", "选1")
                useCoupn(1, 100)
                setBootomPrice(data)
                return
            }
            2 -> {
                Log.e("MXL", "选2")
                useCoupn(1, 200)
                setBootomPrice(data)
                return
            }
        }
    }

    fun setBootomPrice(data: MemberEntity.ProductDetail?) {
        if (couponsentity == null) {
            id_tv_cash?.text = "${data?.cash}"
        } else {
            val oldPrice = data?.cash?.toDouble()
            val disCountPrice = couponsentity?.amount?.toDouble()
            id_tv_cash?.text = (oldPrice?.minus(disCountPrice!!)).toString()
        }

        id_tv_orgin_price?.text = "原价 ¥${data?.originalPrice}"
        id_tv_orgin_price?.getPaint()?.setFlags(Paint.STRIKE_THRU_TEXT_FLAG)
    }

    fun setCouponInfo(entity: CouponsEntity?) {
        setBootomPrice(memberentity)
        if (entity != null) {
            Log.e("MXL", "选择这个优惠券")
            mAdapter?.updateData(entity?.amount.toString())
            id_tv_select_coupons?.text = "您已选择${entity?.amount}元优惠券"
        } else {
            Log.e("MXL", "无优惠券可选")
            mAdapter?.updateData("")
            if (mCouponsResult.isNullOrEmpty()) {
                id_tv_select_coupons?.text = "暂无优惠券"
            } else {
                id_tv_select_coupons?.text = "未选择优惠券"
            }
        }
    }

    override fun onPause() {
        super.onPause()
        isPause = true
    }

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

        } else {
            mLoading?.setResult(false, "支付失败", 1000)
        }
    }

    private var isPause = false
    private var isClickPayBtn = false
    override fun onResume() {
        super.onResume()
        Log.e("MXL", "onResume" + isPause + isClickPayBtn + pay_type)
        if (isPause && isClickPayBtn) {
            if (pay_type == PaymentConfig.MIN_PAY_PROGRAM || pay_type == PaymentConfig.H5_PAY || pay_type == PaymentConfig.ZFB_H5_PAY || pay_type == PaymentConfig.WX_H5_PAY || pay_type == PaymentConfig.HUI_FU_H5_PAY1 || pay_type == PaymentConfig.HUI_FU_H5_PAY2 || pay_type == PaymentConfig.WECHAT_PAY) {
                //如果是敏支付或者H5支付
                Log.e("MXL", "支付完调用")
                mPresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
            } else {
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }
        }
    }

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