package com.zxbw.modulemain.activity

import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxbw.modulemain.R
import com.zxbw.modulemain.box.activity.ReceiveAddressActivity
import com.zxbw.modulemain.box.adapter.OrderAdapter
import com.zxbw.modulemain.box.contract.ShopOrderContract
import com.zxbw.modulemain.box.presenter.ShopOrderPresenter
import com.zxbw.modulemain.view.DialogUtils
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.box.AddressEntity
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.box.OrderEntity
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.pay.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_layout_shop_order.*

class XymhShopOrderActivity : BaseActivity(), ShopOrderContract.View, PayContract.View {
    private var mPresenter: ShopOrderPresenter? = null
    private var mAdapter: OrderAdapter? = null
    private var addressId: String? = ""
    private var depotIds: String? = ""
    private var orderNotes: String? = ""
    private var outTradeNo: String? = ""
    private var mPayresenter: PayContract.Presenter? = null
    private var mLoading: LoadingDialog? = null
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var updateAddress: Observable<Int>? = null
    private var mPayPrice: String? = ""
    var type: String? = "0"
    var addrees: AddressEntity? = 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 = 0
    override fun onClick(v: View?) {

    }

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


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

    override fun init() {
        val list = intent.getStringArrayListExtra(
            "stringList"
        )
        type= intent.getStringExtra("type")
        id_img_back?.setOnClickListener {
            if(TextUtils.equals(type,"1")){
                // 在这里，拦截或者监听Android系统的返回键事件。
                DialogUtils.showExitSkillBuy(this, View.OnClickListener {
                    finish()
                })
            }else{
                finish()
            }
        }

        mPayFunAdapter = PaymentFunAdapter(
            this
        ) { view, position, data ->
            pay_type = data.type ?: 0
            mPayFunAdapter?.setPosition(position)
        }
        id_rcl_shop_payment_list.layoutManager = LinearLayoutManager(this)
        id_rcl_shop_payment_list.adapter = mPayFunAdapter

        id_rl_no_address?.setOnClickListener {
            val intent = Intent(mActivity, ReceiveAddressActivity::class.java)
            intent.putExtra("order", "order")
            startActivityForResult(intent, 1001)

            // JumpUtils.ReceiveAddressReslutJump("0")
        }
        id_rl_hava_address?.setOnClickListener {
            val intent = Intent(mActivity, ReceiveAddressActivity::class.java)
            intent.putExtra("order", "order")
            intent.putExtra("id", addressId)

            startActivityForResult(intent, 1001)

        }
//        id_rl_wechat_pay?.setOnClickListener {
//            pay_type = WECHAT_PAY
//            id_img_wechat?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong)
//            id_img_ali?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong_default)
//        }
//        id_rl_zfb_pay?.setOnClickListener {
//            pay_type = ALI_PAY
//            id_img_wechat?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong_default)
//            id_img_ali?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong)
//
//        }
        id_rl_use_youhui?.setOnClickListener {
            if (ifUseDiscount == false) {
                useDisCount()
            } else {
                noUseDiscount()
            }
        }
        id_tv_to_pay?.setOnClickListener {
            gotoPay()
        }
        initPayConfig()
        mPresenter = ShopOrderPresenter(this)
        val sb = StringBuilder()
        for (dataBean in list) {
            if (sb.length > 0) {
                sb.append(",")
            }
            sb.append(dataBean)
        }
        depotIds = sb.toString()
        mPresenter?.getShopCost(sb.toString(), addressId)
        mAdapter = OrderAdapter(this)
        id_rl_order_goods?.layoutManager = LinearLayoutManager(this)
        id_rl_order_goods?.adapter = mAdapter
        updateAddress = RxBus.get().register(Constant.CHOSSEE_ADDRESS_RESULT, Int::class.java)
        updateAddress?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<Int?> { s ->
                if (s == 1) {
                    updateAddreeInfo(null)
                }

            }, Consumer<Throwable?> { })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1001) {
            addrees = data?.getSerializableExtra("address") as AddressEntity?
            Log.e("MXL", "选了地址回来")
            mPresenter?.getShopCost(depotIds.toString(), addrees?.id)
            updateAddreeInfo(addrees)
        }

    }

    fun updateAddreeInfo(result: AddressEntity?) {
        Log.d("MXL", "updateAddreeInfo")
        if (result == null) {
            id_rl_hava_address?.visibility = View.GONE
            id_rl_no_address?.visibility = View.VISIBLE
            addressId = ""
        } else {
            id_rl_hava_address?.visibility = View.VISIBLE
            id_rl_no_address?.visibility = View.GONE
            addressId = result?.id
            id_tv_user_name_phone?.text =
                result?.username + result?.mobile
            id_tv_user_address?.text =
                "${result?.region}-${result?.address}"
        }


    }

    private var payId: String = ""
    private var totalPrice = ""//使用优惠付的价格
    private var payGoodsId: String = ""
    private var totalPrice2 = ""//不使用付的价格
    private var payGoodsId2: String = ""
    private var discount = ""//优惠的减去的价格

    override fun setOrderData(result: OrderEntity?) {
        mAdapter?.clear()
        mAdapter?.appendToList(result?.goodsList)
        mAdapter?.notifyDataSetChanged()
        totalPrice = result?.totalPrice.toString()
        discount = result?.disCount.toString()
        totalPrice2 = result?.totalPrice2.toString()
        payGoodsId = result?.payGoodsId.toString()
        payGoodsId2 = result?.payGoodsId2.toString()
        mPayPrice = totalPrice
        payId = payGoodsId
        if (TextUtils.equals(discount, "0")) {
            id_rl_use_youhui.visibility = View.GONE
            noUseDiscount()
        } else {
            id_rl_use_youhui.visibility = View.VISIBLE
            useDisCount()
        }
        id_tv_magic_coin_desc.text = "${discount}魔币可抵${discount}元"
        id_tv_yunfei?.text = "${result?.freight}元"
//        if (TextUtils.equals(result?.freight, "0")) {
//            id_rl_yunfei.visibility = View.GONE
//        } else {
//            id_rl_yunfei.visibility = View.VISIBLE
//
//        }
        id_tv_time_trip?.text = result?.text
        id_tv_goods_num?.text = "商品列表(共${result?.goodsList?.size}件商品)"
        if (result?.newText.isNullOrEmpty()) {
            id_rl_youhui_desc.visibility = View.GONE
        } else {
            id_rl_youhui_desc.visibility = View.VISIBLE
            id_rl_youhui_desc.text = "该品最多使用总价${result?.newText}的魔币优惠"
        }
//        if (result?.packingFee!! > 0 && result?.size.equals("1")) {
//            id_rl_dabaofei.visibility = View.VISIBLE
//            id_tv_yunfei_price_trip.text = "打包费"
//            id_tv_price_trip.text = "运费"
//            id_tv_yunfei?.text = "0元"
//            id_tv_dabaofei?.text = "${result?.packingFee}元"
//            mPayPrice = result?.packingFee.toString()
//            payGoodsId = result?.payPackingFeeId ?: ""
//
//        } else {
//            id_rl_dabaofei.visibility = View.GONE
//            id_tv_price_trip.text = "运费"
//            id_tv_yunfei?.text = "${result?.freight}元"
//            mPayPrice = result?.freight
//            payGoodsId = result?.payGoodsId ?: ""
//        }


        if (result?.defaultAddress != null) {
            addressId = result?.defaultAddress?.id
            id_rl_hava_address?.visibility = View.VISIBLE
            id_rl_no_address?.visibility = View.GONE
            id_tv_user_name_phone?.text =
                result?.defaultAddress?.username + result?.defaultAddress?.mobile
            id_tv_user_address?.text =
                "${result?.defaultAddress?.region}-${result?.defaultAddress?.address}"
        } else {
            id_rl_hava_address?.visibility = View.GONE
            id_rl_no_address?.visibility = View.VISIBLE
        }
    }

    override fun creatOrderSucces() {
        if (mLoading != null) {
            mLoading?.dismiss()
        }
        //RxBus.get().post(Constant.order_data_update, 1)
        JumpUtils.OrderSuccessJump()
        finish()
    }

    fun gotoPay() {
        if (TextUtils.isEmpty(addressId)) {
            Utils.showToast(this, "请填写地址")
            return
        }
        orderNotes = id_edit_beizhu?.text.toString()
        if (mPayPrice?.toDouble()!! > 0) {
            if (pay_type == 0) {
                Utils.showToast(this, "请选择支付类型")
                return
            }
            mLoading?.show()
            mLoading?.setLoading("请稍后")
            if (pay_type == 1||pay_type==13||pay_type==21||pay_type==PaymentConfig.SD_PAY) {
                mPayresenter?.shoprequestAliPay(
                    "xxsqshop://shoporder",
                    this,
                    payId ?: "",
                    pay_type.toString(),
                    "8",
                    addressId.toString(),
                    mdiscount.toString(),
                    depotIds.toString(),
                    orderNotes.toString()
                )
            } else {
                mPayresenter?.shoprequestWechatPayOrder(
                    payId ?: "",
                    pay_type.toString(),
                    "8",
                    addressId.toString(),
                    mdiscount.toString(),
                    depotIds.toString(),
                    orderNotes.toString()
                )
            }
        } else {
            mLoading?.show()
            mLoading?.setLoading("请稍后")
            mPresenter?.createOrder(addressId, depotIds, orderNotes)
        }
    }


    fun initPayConfig() {
        mPayresenter = PayPresenter(this)
        mPayresenter?.appInfo()
        mLoading = LoadingDialog.getLoadingDialog(
            mActivity,
            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("member_page_pay_query_order", "微信付款成功")
                    mPayresenter?.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 fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            mLoading?.setResult(true, "支付成功", 1000)
        } else {
            mLoading?.setResult(false, "支付失败", 1000)
        }

    }

    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {

    }

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

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

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

    override fun requestH5OrderSuc(form: String) {
        if (form.isEmpty()) {
            EventUtils.onEvent("h5_pay_error")
            showResultLoading(false)
        } else {
            if (pay_type == PaymentConfig.H5_PAY) {
                loadH5Pay(form)
            } else {
                H5PayUtil().loadH5AppPay(
                    this,
                    pay_type!!,
                    form ?: "",
                    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)
                            }
                        }
                    })
            }
        }
    }

    override fun verifyOrderSuc(orsder: String) {
        showResultLoading(true)
        EventUtils.onEvent("CREATE_ORDER", "创建订单")
        creatOrderSucces()
//        id_rl_hava_address?.postDelayed({
//            mPresenter?.createOrder(addressId, depotIds, orderNotes)
//        }, 500)

    }

    override fun setCanInvest(boolean: Boolean?) {

    }

    override fun setOrderNo(order: String?) {
        outTradeNo = order
    }

    private var mPayFunAdapter: PaymentFunAdapter? = null;

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null && !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 ?: 0
                    mPayFunAdapter?.setPosition(i)
                    break
                }
            }
        }

    }

    //使用优惠
    var ifUseDiscount: Boolean? = true
    var mdiscount: String? = ""
    fun useDisCount() {
        id_tv_youhui.text = "-¥ ${discount}"
        ifUseDiscount = true
        id_img_chosse_youhui.setImageResource(R.drawable.icon_xuanzhong)
        if (TextUtils.equals(SettingPreference.getBuyMode(), "1")) {
            Log.e("MXL", "人民币购买" + SettingPreference.getGoodPrice())
            id_rl_use_youhui.visibility = View.GONE
            id_tv_pay_money.text = SettingPreference.getGoodPrice()
            mdiscount = ""
            payId = SettingPreference.getGoodPrice()
            mPayPrice = SettingPreference.getGoodPrice()

        } else {
            Log.e("MXL", "魔比购买")
            id_rl_use_youhui.visibility = View.VISIBLE
            id_tv_pay_money.text = totalPrice
            mdiscount = discount
            payId = payGoodsId
            mPayPrice = totalPrice
        }


    }

    //不使用优惠
    fun noUseDiscount() {
        ifUseDiscount = false
        id_tv_youhui.text = "-¥ ${discount}"
        id_img_chosse_youhui.setImageResource(R.drawable.icon_xuanzhong_default)
        id_tv_pay_money.text = totalPrice2
        payId = payGoodsId2
        mPayPrice = totalPrice2
        mdiscount = "0"
    }

    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
                    mPayresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type!!)
                } else {
                    showResultLoading(false)
                }
            }
        }
    }

    private var isPause = false
    override fun onPause() {
        super.onPause()
        isPause = true

    }

    override fun onResume() {
        super.onResume()
        if (isPause) {
            mHandler?.sendEmptyMessageDelayed(0, 2000)
        }
        if (isPause) {
            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) {
                //如果是敏支付或者H5支付
                mPayresenter?.verifyPay(SettingPreference.getOutTradeNo(), pay_type)
            } else {
                mHandler?.sendEmptyMessageDelayed(0, 2000)
            }
        }
    }

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

    private fun loadH5Pay(form: String) {
        val webSettings = id_shop_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_shop_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)
                        EventUtils.onEvent("h5_open_zfb_suc")
                        return true
                    }
                } catch (e: Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    EventUtils.onEvent("h5_open_zfb_error", e.toString())
                    showResultLoading(false)
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                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_shop_pay_web_view?.loadUrl("javascript:loadPayHtml('$form')");
                }
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                // 接受所有网站的证书，忽略SSL错误，执行访问网页
                handler?.proceed();
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    Log.d("wxw", "1error${error?.errorCode}")
                    Log.d("wxw", "2error${error?.description}")
                    Log.d("wxw", "3error${error?.toString()}")
                    EventUtils.onEvent(
                        "h5_pay_error1",
                        "code: ${error?.errorCode} desc: ${error?.description}"
                    )
                } else {
                    EventUtils.onEvent("h5_pay_error1", error.toString())
                }
                showResultLoading(false)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    if (request?.url?.path?.endsWith("/favicon.ico") == true) {

                    } else {
                        Log.d("wxw", "1errorResponse?.statusCode${request?.url}")
                        Log.d("wxw", "2errorResponse?.statusCode${errorResponse?.statusCode}")
                        EventUtils.onEvent(
                            "h5_pay_error2",
                            errorResponse?.statusCode.toString() + " url:${request?.url}"
                        )
                        showResultLoading(false)
                    }
                } else {
                    EventUtils.onEvent("h5_pay_error2", errorResponse.toString())
                    showResultLoading(false)
                }
                super.onReceivedHttpError(view, request, errorResponse)

            }
        }
        id_shop_pay_web_view.loadUrl(NetConfig.H5.WEB_URL_H5_PAY)

    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(TextUtils.equals(type,"1")){
                // 在这里，拦截或者监听Android系统的返回键事件。
                DialogUtils.showExitSkillBuy(this, View.OnClickListener {
                    finish()
                })

            }else{
                finish()
            }

        }

        return false
    }
}