package com.zj365.dc.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseVmAct
import com.xty.common.*
import com.xty.common.aMapUtils.AmapInit
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.*
import com.xty.common.event.BindDevEvent
import com.xty.common.event.BlueToothConnectEvent
import com.xty.common.event.BluetoothEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.xqr_code.XQRCodeAct


import com.xuexiang.xqrcode.XQRCode
import com.zj365.dc.databinding.ActDeviceActiveBinding
import com.zj365.dc.model.ScanInfoBean
import com.zj365.dc.vm.BasicInfoVm
import com.zj365.health.weight.SignDialog
import com.zj365.mime.weight.FactorySettingDialog
import com.zj365.mime.weight.NoticeSettingDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pub.devrel.easypermissions.EasyPermissions

/**
 *
 * 设备激活
 */
@SuppressLint("ObsoleteSdkInt")
@Route(path = ARouterUrl.DEVICE_ACTIVE)
class DeviceActiveAct : BaseVmAct<BasicInfoVm>() {

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

    //    var user: SettingBean.User? = null
    var signPath = ""//签名地址
    var isAgree = false
    val SERVER_AGREEMENT = 1000 //服务协议
    var isLogin: Boolean = false

    //签名
    val dialog by lazy {
        SignDialog(this) {
            signPath = it
            binding.mImageSign.setImage(this, it)
        }
    }

    private val factorySettingDialog by lazy {
        FactorySettingDialog(
            this,
            "蓝牙手表需要访问位置、蓝牙权限。"
        ) {
            getBluePermission(baseContext) {
                if (it) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && !isGpsOpen(baseContext)
                    ) {
                        requestGPSPermission()
                    }
                } else {
                    finish()
                }
            }
        }
    }

    private var headerPath = ""
    private var name = ""
    private var sexType = ""
    private var idCard = ""
    private var height = ""
    private var wieght = ""
    private var address = ""
    private var otherName = ""
    private var otherPhone = ""
    private var rela = ""
    private var provincey = ""
    private var city = ""
    private var district = ""
    private var lat = ""
    private var lng = ""
    private var medicName = ""
    private var medicIds = ""
    private var diseaseList = ""
    private var birthDay = ""
    private var birthdayType = -1
    private var type = 0//0:蓝牙设备 默认 1:4G设备
    private var watchName = ""

    override fun initData() {
        super.initData()
        isDarkBar = true
        isLogin = intent.getBooleanExtra("isLogin", false)
        intent.extras?.let {
            headerPath = getIntentStringData(it, "headerPath")
            name = getIntentStringData(it, "name")
            sexType = getIntentStringData(it, "sexType")
            idCard = getIntentStringData(it, "idCard")
            height = getIntentStringData(it, "height")
            wieght = getIntentStringData(it, "wieght")
            address = getIntentStringData(it, "address")
            otherName = getIntentStringData(it, "otherName")
            otherPhone = getIntentStringData(it, "otherPhone")
            rela = getIntentStringData(it, "rela")
            provincey = getIntentStringData(it, "provincey")
            city = getIntentStringData(it, "city")
            district = getIntentStringData(it, "district")

            lat = getIntentStringData(it, "lat")
            lng = getIntentStringData(it, "lng")
            medicName = getIntentStringData(it, "medicName")

            medicIds = getIntentStringData(it, "medicIds")
            diseaseList = getIntentStringData(it, "diseaseList")
            birthDay = getIntentStringData(it, "birthDay")

            birthdayType = it.getInt("birthdayType", -1)
            type = it.getInt("type", 0)
        }

    }

    private fun getIntentStringData(it: Bundle, key: String): String {
        return if (it.getString(key).isNullOrEmpty()) "" else it.getString(key).toString()
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = getString(R.string.active_action)
        binding.title.mIvBack.setOnClickListener {
            if (isLogin) { //如果是走注册流程过来的，退出该界面，则进入主界面
                RouteManager.goAct(ARouterUrl.MAIN_ACT)
                RxActivityTool.finishAllActivity()
            } else {
              /*  EventBus.getDefault().post(BindDevEvent())
                CommonToastUtils.showToast("绑定成功")*/
                finish()
            }
        }

        binding.mSign.setOnClickListener {//签名信息填写
            dialog.show()
        }

        binding.mSubmit.setOnClickListener {
            submitData()
        }

        if (type == 0) {//是蓝牙设备
            factorySettingDialog.isShow()

            binding.mBlueTooth.setOnClickListener {//蓝牙设备搜索绑定
                RxKeyboardTool.hideSoftInput(this)
                bundle.clear()
                bundle.putString("devMac", if (it.tag == null) "" else it.tag.toString())
                bundle.putString("devName", (it as TextView).text.toString())
                RouteManager.goAct(ARouterUrl.DEVICE_CONNECT, bundle)
            }
            binding.mDeviceLayout.visibility = View.VISIBLE
            if (YCBBlueConnectHelper.getBlueStatus(false)) {//如果当前已经连接手表
                binding.mBlueTooth.text = Const.connectBlueDevice.deviceName
                binding.mBlueTooth.tag = Const.connectBlueDevice.deviceMac
            }
        } else {//4G设备
            binding.mDeviceLayout.visibility = View.GONE
            binding.title.mIvReight.apply {
                visibility = View.VISIBLE
                setImageResource(com.zj365.health.R.mipmap.ic_scan)
                setOnClickListener {
                    startScan()
                }
            }
        }
        setPrive()
    }

    private val reqGpsPermissionDialog by lazy {
        NoticeSettingDialog(this, "请打开GPS权限", {
            finish()
        }) {
            // 转到手机设置界面，用户设置GPS
            var intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivityForResult(intent, 1001); // 设置完成后返回到原来的界面
        }
    }


    private fun requestGPSPermission() {
        reqGpsPermissionDialog.show()
    }

//    /**
//     * 检测拍摄权限
//     */
//    private fun checkCameraPermissions() {
//        val permission = arrayOf(Manifest.permission.CAMERA)
//        Acp.getInstance(this).request(
//            AcpOptions.Builder()
//                .setPermissions(
//                    *permission
//                ).build(),
//            object : AcpListener {
//                override fun onGranted() {
//
//                }
//
//                override fun onDenied(permissions: List<String>) {
//                    finish()
//                }
//            })
//    }

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

    }

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

    /**
     * 隐私协议
     */
    private fun setPrive() {
        binding.mPrivate.setOnClickListener {
            if (!isAgree) {
                forwardPrivate()
                return@setOnClickListener
            }
            it.isSelected = !it.isSelected
        }
        binding.mPrivate.movementMethod = MyLinkedMovementMethod().getInstance()
        var span = SpannableString(getString(R.string.agree_private_active))
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                forwardPrivate()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color =
                    ContextCompat.getColor(this@DeviceActiveAct, R.color.col_02c)
                ds.isUnderlineText = false
            }

        }, 2, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.mPrivate.text = span
        binding.mPrivate.highlightColor = Color.TRANSPARENT
    }

    /**
     * 跳转至隐私协议页面
     */
    private fun forwardPrivate() {
        bundle.clear()
        bundle.putString("title", "服务协议")
        bundle.putInt("type", Const.AGREEMENT_6)
        RouteManager.goActRequest(
            ARouterUrl.RICH_TEXT,
            this@DeviceActiveAct,
            SERVER_AGREEMENT,
            bundle
        )
    }


    private fun submitData() {
        RxKeyboardTool.hideSoftInput(this)
        if (!isAgree) {
            CommonToastUtils.showToast(R.string.please_agree_server)
            return
        }

        if (type == 0 && binding.mBlueTooth.text.isNullOrEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_device_code)
            return
        }

        if (signPath.isNullOrEmpty()) {
            CommonToastUtils.showToast("请完善签名")
            return
        }

        if (binding.mDevNum.text.isNullOrEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_device_code)
            return
        }

        if (binding.mActiveCode.text.isNullOrEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_active_code)
            return
        }

        var devMc = if (type == 0) {
            if (binding.mBlueTooth.tag == null) "" else binding.mBlueTooth.tag as String
        } else {//4G直接传设备号
            binding.mDevNum.text.toString()
        }

        var devName = if (type == 0) {
            binding.mBlueTooth.text.toString()
        } else {
            if (watchName.isNullOrEmpty()) {
                if (devMc.startsWith("818") && devMc.length > 6) {
                    "A3-${devMc.substring(devMc.length - 7)}"
                } else {
                    "4G-$devMc"
                }
            } else {
                watchName
            }
        }

        if (otherPhone.isNullOrEmpty() || height.isNullOrEmpty() || wieght.isNullOrEmpty() || otherName.isNullOrEmpty()) {
            mViewModel.activeDevice(
                signPath,
                binding.mDevNum.text.toString(),
                binding.mActiveCode.text.toString(),
                devMc,
                devName
            )
        } else {
            mViewModel.submit(
                headerPath,
                name,
                sexType,
                idCard,
                height,
                wieght,
                address,
                otherName,
                otherPhone,
                rela,
                provincey,
                city,
                district,
                lat,
                lng,
                medicName,
                medicIds,
                signPath,
                binding.mDevNum.text.toString(),
                binding.mActiveCode.text.toString(),
                devMc,
                devName,
                diseaseList,
                birthDay,
                birthdayType
            )
        }
    }

    /**
     * 设置扫码信息
     */
    private fun setScanInfo(scanInfo: ScanInfoBean) {
        binding.mDevNum.setText(scanInfo.deviceCode)
        binding.mActiveCode.setText(scanInfo.activationCode)
        watchName = scanInfo.watchName
    }


    override fun onRestart() {
        super.onRestart()
        if (type == 0) {//是蓝牙设备
            factorySettingDialog.isShow()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode === RESULT_OK) {
            when (requestCode) {
                SERVER_AGREEMENT -> {
                    isAgree = true
                    binding.mPrivate.isSelected = isAgree
                }

                XQRCodeAct.QRCODE_AGREEMENT -> {
                    when (data!!.getIntExtra(XQRCode.RESULT_TYPE, 0)) {
                        XQRCode.RESULT_SUCCESS -> {
                            try {
                                val result = data.extras!!.getString(XQRCode.RESULT_DATA)
                                LogUtils.d("扫描结果:$result")
                                if (!result.isNullOrEmpty()) {
                                    val gson = Gson()
                                    setScanInfo(gson.fromJson(result, ScanInfoBean::class.java))
                                } else {
                                    CommonToastUtils.showToast("扫码失败,请重试...")
                                }
                            } catch (e: Exception) {
                                LogUtils.e("二维码扫描：$e")
                                CommonToastUtils.showToast("请确认二维码是否正确！")
                            }
                        }

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


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun bloothConnect(event: BluetoothEvent) {
        binding.mBlueTooth.text = event.devName
        binding.mBlueTooth.tag = event.devMac
    }

    private var isActiveSuccess = false
//    private val dialogWear by lazy {
//        WearDialog(this) {
//            RouteManager.goAct(ARouterUrl.MAIN_ACT)
//            finish()
//        }
//    }

    override fun liveObserver() {
        mViewModel.activeLive.observe(this) {
            activeSuccess()
        }
        mViewModel.setBasic.observe(this) {
            activeSuccess()
        }
//        mViewModel.prevLive.observe(this) {
//            dialogWear.showContent(it.data.content)
//        }
    }

    private fun activeSuccess() {
        isActiveSuccess = true
        CommonToastUtils.showSucceedToast("设备激活成功")
        LogUtils.d("设备激活成功")
        MMkvHelper.put(Const.Watch_Device_Type, type)
        if (type == 0) {
            YCBManager.deleteHistory(YCBOrder.DELETE_LocalALL)
            EventBus.getDefault().post(BlueToothConnectEvent())
        }
        EventBus.getDefault().post(MyInfoEvent())
        EventBus.getDefault().post(BindDevEvent())
      //  CommonToastUtils.showToast("绑定成功")
        finish()
       /* if (CommonUtils.getMyUserInfo() == null) {
            bundle.clear()
            bundle.putInt("isBind", 0)
            RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE, bundle)
            finish()
        }
        CommonUtils.getMyUserInfo()?.let { bean ->
            if (bean.urgentPhone.isNullOrEmpty()) {//如果紧急联系人电话并且签名为空则认为没有完善信息
                bundle.clear()
                bundle.putInt("isBind", 0)
                RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE, bundle)
                finish()
            } else {
                RouteManager.goAct(ARouterUrl.MAIN_ACT)
                finish()
            }
        }*/
//        mViewModel.getPrev(7)
    }

    override fun onDestroy() {
        AmapInit.stopLocation()
        if (!isActiveSuccess && type == 0) {
            YCBBlueConnectHelper.disconnect()
        }
        super.onDestroy()
    }

    override fun onBackPressed() {
        if (isLogin) { //如果是走注册流程过来的，退出该界面，则进入主界面
            RouteManager.goAct(ARouterUrl.MAIN_ACT)
            RxActivityTool.finishAllActivity()
        } else {
            super.onBackPressed()
        }
    }
}