package com.zj365.health.act

import android.Manifest
import android.content.Intent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.xty.base.act.BaseVmAct
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.NSuanOpenEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.PermissionUtils
import com.xty.common.xqr_code.XQRCodeAct
import com.xty.common.xqr_code.XQRCodeAct.Companion.QRCODE_AGREEMENT
import com.zj365.health.R
import com.zj365.health.databinding.ActNsuanOpenBinding
import com.zj365.health.vm.NSuanVm
import com.xuexiang.xqrcode.XQRCode
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pub.devrel.easypermissions.EasyPermissions

/**
 * 尿酸开通
 */
@Route(path = ARouterUrl.NS_OPEN)
class NSuanOpenAct : BaseVmAct<NSuanVm>() {

    val binding by lazy { ActNsuanOpenBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

    private var isOpen = false
    var userId = ""
    var time:String?=null

    override fun initData() {
        super.initData()
        isDarkBar = true//设置状态栏字体为深色
        intent.extras?.let {
            isOpen = it.getBoolean("isOpen", false)
            userId = it.getString("id").toString()
            time = it.getString("time")
        }
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text =
            if (isOpen) getString(R.string.ns_renew) else getString(R.string.ns_open)

        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }

        binding.mConfirm.isSelected = true

        binding.mTvConvert.setOnClickListener(onClickListener)
        binding.mPrivate.setOnClickListener(onClickListener)
        binding.mConfirm.setOnClickListener(onClickListener)
        binding.llScan.setOnClickListener {
            startScan()
        }
    }

    private val onClickListener = View.OnClickListener {
        when (it.id) {
            //获取兑换码
            R.id.mTvConvert -> {
                bundle.clear()
                RouteManager.goAct(ARouterUrl.NS_HOW_OPEN)
            }
            //开通须知
            R.id.mPrivate -> {
                binding.mPrivate.isSelected = !binding.mPrivate.isSelected
            }
            //下一步按钮
            R.id.mConfirm -> {
                confirm()
            }
        }
    }

    /**
     * 扫码
     */
    private fun startScan() {
        if(EasyPermissions.hasPermissions(this,
                Manifest.permission.CAMERA)){
            XQRCodeAct.start(
                this@NSuanOpenAct,
                QRCODE_AGREEMENT,
                R.style.XQRCodeTheme_Custom
            )
        }else{
            EasyPermissions.requestPermissions(this,"",
                0x00011,
                Manifest.permission.CAMERA)
        }
    }

    override fun onSuccess(requestCode: Int) {
        super.onSuccess(requestCode)
        XQRCodeAct.start(
            this@NSuanOpenAct,
            QRCODE_AGREEMENT,
            R.style.XQRCodeTheme_Custom
        )
    }

    private fun confirm() {
        if (binding.mTvActCode.text.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入激活码")
            return
        }
        if (!binding.mPrivate.isSelected) {
            CommonToastUtils.showToast("请阅读开通须知")
            return
        }

        bundle.clear()
        bundle.putString("id",userId)
        bundle.putString("activeCode",binding.mTvActCode.text.toString())
        bundle.putString("time",time)
        RouteManager.goAct(ARouterUrl.NS_MESSAGE_PERFECT,bundle)
//        finish()
//        mViewModel.nsOpen(userId, binding.mTvActCode.text.toString())
    }

    override fun liveObserver() {
        mViewModel.nsuanOpen.observe(this) {
            if (null == it.data) {
                LogUtils.e("操作异常！")
                return@observe
            }
            val code = it.code
            if (code != 0) {
                if (isOpen) {
                    CommonToastUtils.showToast("续费失败：${it.msg}")
                } else {
                    CommonToastUtils.showToast("开通失败：${it.msg}")
                }
                return@observe
            } else {
                if (isOpen) {
                    CommonToastUtils.showSucceedToast("续费成功")
                } else {
                    CommonToastUtils.showSucceedToast("开通成功")
                }
            }
            EventBus.getDefault().post(NSuanOpenEvent())
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode === RESULT_OK) {
            when (requestCode) {
                QRCODE_AGREEMENT -> {
                    var type = data!!.getIntExtra(XQRCode.RESULT_TYPE, 0)
                    when (type) {
                        XQRCode.RESULT_SUCCESS -> {
                            try {
                                var result = data!!.extras!!.getString(XQRCode.RESULT_DATA)
                                LogUtils.d("扫描结果:$result")
                                if (!result.isNullOrEmpty()) {
                                    val gson = Gson()
                                    //设置扫描结果
                                    binding.mTvActCode.setText(result)
                                } else {
                                    CommonToastUtils.showToast("扫码失败,请重试...")
                                }
                            } catch (e: Exception) {
                                LogUtils.e("二维码扫描：$e")
                                CommonToastUtils.showToast("请确认二维码是否正确！")
                            }
                        }

                        XQRCode.RESULT_FAILED -> {
                            LogUtils.d("扫描失败")
                        }
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefresh(event: NSuanOpenEvent) {
       finish()
    }
}