package com.zxhl.main.page.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
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.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.pay.PayActivity
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.pay.PayPresenter
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.main.R
import com.zxhl.main.page.adapter.OrderAdapter
import com.zxhl.main.page.contract.OrderDetailContract
import com.zxhl.main.page.presenter.OrderDetailPresenter
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_layout_order_detail.*
import kotlinx.android.synthetic.main.activity_layout_order_detail.id_img_ali
import kotlinx.android.synthetic.main.activity_layout_order_detail.id_img_back
import kotlinx.android.synthetic.main.activity_layout_order_detail.id_img_wechat
import kotlinx.android.synthetic.main.activity_layout_order_detail.id_rl_wechat_pay
import kotlinx.android.synthetic.main.activity_layout_order_detail.id_rl_zfb_pay
class OrderDetailActivity : BaseActivity(), OrderDetailContract.View, PayContract.View {
    private var mPresenter: OrderDetailPresenter? = 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 addrees: AddressEntity? = null

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

    private var pay_type = 0
    override fun onClick(v: View?) {

    }

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


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

    override fun init() {
        val list = intent.getStringArrayListExtra(
            "stringList"
        )
        id_img_back?.setOnClickListener {
            finish()
        }
        id_tv_kefu?.setOnClickListener {
            JumpUtils.webJump("客服", NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
        }
        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 = MINI_PROGRAM
            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_tv_to_pay?.setOnClickListener {
            gotoPay()
        }
        initPayConfig()
        mPresenter = OrderDetailPresenter(this)
        val sb = StringBuilder()
        for (dataBean in list) {
            if (sb.length > 0) {
                sb.append(",")
            }
            sb.append(dataBean)
        }
        depotIds = sb.toString()
        mPresenter?.getShipping(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?.getShipping(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 payGoodsId: String = ""
    override fun setOrderData(result: OrderEntity?) {
        mAdapter?.clear()
        mAdapter?.appendToList(result?.goodsList)
        mAdapter?.notifyDataSetChanged()
        if (result?.size != null) {
            if (result?.size!!.toIntOrNull()!! >= 3) {
                id_rl_bao_you.visibility = View.VISIBLE
            } else {
                id_rl_bao_you.visibility = View.GONE
            }
        }


        id_tv_goods_num?.text = "商品列表(共${result?.size}件商品)"
        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}元"
            id_tv_pay_price?.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}元"
            id_tv_pay_price?.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) {
                mPayresenter?.requestAliPay(this, payGoodsId ?: "", pay_type.toString(), "7")
            } else {
                mPayresenter?.requestMiniProgrom(payGoodsId ?: "", pay_type.toString(), "7")
            }
        } else {
            mLoading?.show()
            mLoading?.setLoading("请稍后")
            mPresenter?.createOrder(addressId, depotIds, orderNotes, outTradeNo)
        }
    }


    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 {
                    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() {
        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 verifyOrderSuc(orsder: String) {
        showResultLoading(true)
        EventUtils.onEvent("CREATE_ORDER","创建订单")

        id_rl_hava_address?.postDelayed({
            mPresenter?.createOrder(addressId, depotIds, orderNotes, outTradeNo)
        }, 500)

    }

    override fun setCanInvest(boolean: Boolean?) {

    }

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

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null) {
            id_tv_depots_text?.text=result?.depots_text
            if (result.pay_ali.equals("1") && result.pay_wx.equals("0")) {
                pay_type = PayActivity.ALI_PAY
                id_rl_wechat_pay.visibility = View.GONE
                id_rl_zfb_pay.visibility = View.VISIBLE
                id_img_ali?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong)
            } else {
                if (result?.pay_ali.equals("0")) {
                    id_rl_zfb_pay.visibility = View.GONE
                } else {
                    id_rl_zfb_pay.visibility = View.VISIBLE
//                pay_type = PayActivity.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)
                }
                if (result?.pay_wx.equals("0")) {
                    id_rl_wechat_pay.visibility = View.GONE
                } else {
                    id_rl_wechat_pay.visibility = View.VISIBLE
                    pay_type = PayActivity.MINI_PROGRAM
                    id_img_wechat?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong)
                    id_img_ali?.setImageResource(com.zxhl.cms.R.drawable.icon_xuanzhong_default)
                }
            }
        }
    }

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

    }

    override fun onResume() {
        super.onResume()
        if (isPause) {
            mHandler?.sendEmptyMessageDelayed(0, 2000)
        }

    }

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