package com.medical.ydl.medical.pay

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import com.alipay.sdk.app.PayTask
import com.medical.ydl.medical.bean.CreatePayReqDtoBody
import com.medical.ydl.medical.bean.CreatePayRespose
import com.medical.ydl.medical.dialog.TimeBackDialog
import com.medical.ydl.medical.http.MedicalPayServiceImpl
import com.medical.ydl.medical.modular.MedicalPayIn
import com.medical.ydl.medical.pay.bean.MedicalPayResult
import com.medical.ydl.medical.pay.bean.MedicalPayStatus
import com.medical.ydl.medical.pay.bean.MedicalWXPayEvent
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.BaseResponse
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.yidianling.common.tools.ToastUtil
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.medical_pay_activity.*
import java.util.*

/**
 * 医疗 支付页
 * */

class MedicalPayActivity : BaseActivity() {
    companion object {
        private const val PRICE_KEY = "price"
        private const val ORDER_KEY = "orderId"
        private const val DOCTORUID_KEY = "doctorUid"
        private lateinit var mPrice: String
        private lateinit var mOrderId: String
        private lateinit var mDoctorUid: String

        private var timer: CountDownTimer? = null

        //阿里支付
        private const val PAY_ALI = 1

        //微信支付
        private const val PAY_WECHAT = 3

        /**
         * 已选择支付方式
         */
        private var payType = PAY_WECHAT

        /**
         * @param price 价格
         * @param orderId 订单id
         * */
        @JvmStatic
        fun start(context: Context, price: String, orderId: String, doctorUid: String) {
            val starter = Intent(context, MedicalPayActivity::class.java)
                .putExtra(PRICE_KEY, price)
                .putExtra(ORDER_KEY, orderId)
                .putExtra(DOCTORUID_KEY, doctorUid)
            context.startActivity(starter)
        }

        @SuppressLint("HandlerLeak")
        private val mHandler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    PAY_ALI -> {
                        val payResult = MedicalPayResult(msg.obj as Map<String?, String?>)

                        /**
                         * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                        val resultStatus: String = payResult.getResultStatus()
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            LogUtil.e(resultStatus)
                            EventBus.getDefault().post(MedicalWXPayEvent(MedicalPayStatus(true)))
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            LogUtil.e(resultStatus)
                            EventBus.getDefault().post(MedicalWXPayEvent(MedicalPayStatus(false)))
                        }
                    }

                    else -> {
                    }
                }
            }
        }
    }

    override fun layoutResId(): Int {
        return R.layout.medical_pay_activity
    }

    override fun initDataAndEvent() {
        EventBus.getDefault().register(this)

        initStatus()
        mPrice = intent.getStringExtra(PRICE_KEY)
        mOrderId = intent.getStringExtra(ORDER_KEY)
        mDoctorUid = intent.getStringExtra(DOCTORUID_KEY)
        payType = PAY_WECHAT

        price.text = mPrice
        ll_alipay.setOnClickListener {
            //选择阿里支付
            payType = PAY_ALI
            iv_wx_check.setImageResource(R.mipmap.medical_pay_uncheck)
            iv_alipay_check.setImageResource(R.mipmap.medical_pay_check)
        }

        ll_wx_pay.setOnClickListener {
            //选择微信
            payType = PAY_WECHAT

            iv_wx_check.setImageResource(R.mipmap.medical_pay_check)
            iv_alipay_check.setImageResource(R.mipmap.medical_pay_uncheck)

        }

        iv_back.setOnClickListener {
            backCheck()
        }



        to_pay.setOnClickListener {
            //支付按钮
            MedicalPayServiceImpl.getOrderInfo(
                CreatePayReqDtoBody(
                    mPrice,
                    mOrderId,
                    payChannel = payType
                )
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    if (response.code == 200) {
                        toPay(response, payType)
                    }

                }, { e ->
                    e.printStackTrace()
                })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("CheckResult")
    private fun backCheck() {
        //获取订单结束时间
        MedicalPayServiceImpl.getSurplusPayTime(mOrderId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                if (response.code == 200) {
                    showCloseDialog(response.data.surplusPayTime)
                } else {
                    finish()
                }
            }, { e ->
                finish()
                e.printStackTrace()
            })


    }

    /**
     * 关闭弹窗
     * */
    private fun showCloseDialog(timeStamp: Long) {
        val builder = TimeBackDialog.Builder(this@MedicalPayActivity, "center", true)
        builder.setTitle("")
        builder.setMessage("\n已为您锁定问诊名额，请在24小时59分00秒内完成支付，超时名额自动取消\n")
        builder.setPositiveButton(
            "继续支付"
        ) { dialog, which ->
            timer?.cancel()
            dialog.dismiss()
        }.setNegativeButton(
            "确定离开"
        ) { dialog, which ->
            //关闭页面
            timer?.cancel()
            finish()
            dialog.dismiss()
        }
        builder.setRight_color("#3464EC")
        builder.setLeft_color("#8595A9")
        builder.setContent_color("#10233A")
        val dialog = builder.create()
        dialog.show()

        timer = object : CountDownTimer(timeStamp * 1000, 1) {
            override fun onTick(millisUntilFinished: Long) {
                //单位时
                var hour = millisUntilFinished / (1000 * 60 * 60)
                //单位分
                var minute =
                    (millisUntilFinished - hour * (1000 * 60 * 60)) / (1000 * 60)
                //单位秒
                var second =
                    (millisUntilFinished - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000

                builder.setMessageToTextView("${hour}小时${minute}分${second}")
            }

            override fun onFinish() {
                builder.dismiss()
                finish()
            }


        }
        timer?.start()
    }

    private fun toPay(response: BaseResponse<CreatePayRespose>, payType: Int) {
        if (payType == PAY_ALI && response.data.payParams.isNotEmpty()) {
            val payRunnable = Runnable {
                val alipay = PayTask(this@MedicalPayActivity)
                val result = alipay.payV2(response.data.payParams, true)
                Log.i("msp", result.toString())
                val msg = Message()
                msg.what = payType
                msg.obj = result
                mHandler.sendMessage(msg)

            }
            // 必须异步调用
            var payThread = Thread(payRunnable)
            payThread.start()
        } else if (payType == PAY_WECHAT) {
            var option = response.data
            val api = WXAPIFactory.createWXAPI(applicationContext, option.appid, true)
            if (api.wxAppSupportAPI < Build.PAY_SUPPORTED_SDK_INT) {
                ToastUtil.toastShort("目前您的微信版本过低或未安装微信，需要安装微信才能使用")
            }
            api.registerApp(option.appid)
            val request = PayReq()
            request.appId = option.appid
            request.partnerId = option.partnerid
            request.prepayId = option.prepayid
            request.packageValue = option.packageValue
            request.nonceStr = option.noncestr
            request.timeStamp = option.timestamp
            request.sign = option.sign
            api.sendReq(request)

        } else {
            ToastUtil.toastShort("支付类型出错")
        }

    }

    private fun initStatus() {
        StatusBarUtils.setTransparentForImageView(this@MedicalPayActivity, null)
        StatusBarUtils.statusBarLightMode(this@MedicalPayActivity)
    }

    fun onEvent(event: MedicalWXPayEvent) {
        if (event.status.success) {
            MedicalPayIn.mainIntentMessage(this@MedicalPayActivity, mDoctorUid)
            ToastUtil.toastShort("支付成功")
            finish()
        } else {
            ToastUtil.toastShort("支付失败")
        }
    }

    override fun onBackPressed() {
        backCheck()
    }
}