package com.zj365.dc.activity

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.blankj.utilcode.util.ArrayUtils
import com.google.android.material.bottomnavigation.BottomNavigationItemView
import com.google.android.material.bottomnavigation.BottomNavigationMenuView
import com.lifesense.android.ble.core.serializer.AbstractMeasureData
import com.lifesense.android.ble.device.fatscale.model.WeightMeasureData
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxSPTool
import com.xty.base.act.BaseVmAct
import com.xty.base.dialog.AppUpdateDialog
import com.xty.base.dialog.DialogActivities
import com.xty.base.vp2.VpAdapter
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.aMapUtils.AmapInit
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.checkBlueConnectPermission
import com.xty.common.event.AddSuccessEvent
import com.xty.common.event.BindDevEvent
import com.xty.common.event.LoginOrRegisterEvent
import com.xty.common.event.MeasureWeightEvent
import com.xty.common.event.MqttReceive
import com.xty.common.event.MyInfoEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.util.ViewScreenshotUtils
import com.xty.network.model.InviteCustodyBean
import com.zj365.dc.BuildConfig
import com.zj365.dc.R
import com.zj365.dc.databinding.ActivityMainBinding
import com.zj365.dc.fragment.DynamicManagementFrag
import com.zj365.dc.fragment.HealthHomeFrag
import com.zj365.dc.fragment.MessageFragment
import com.zj365.dc.fragment.MineFrag
import com.zj365.dc.fragment.ShopFragment
import com.zj365.dc.vm.MainVm
import com.zj365.health.act.binddevice.BaseDeviceBindListAct
import com.zj365.health.act.binddevice.BlueUtil
import com.zj365.health.weight.DialogTipNew
import com.zj365.mime.act.DevInfoAct
import io.reactivex.functions.Consumer
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Date

@Route(path = ARouterUrl.MAIN_ACT)
class MainActivity : BaseVmAct<MainVm>(), Consumer<AbstractMeasureData>  {

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

    private var isonNewIntent: Boolean = false
    var isDemonstrate: Boolean = false
    var imunreadCount = 0
    var sysunreadCount = 0
    var isDialogShow = false  //是否已经弹出Dialog
    private var unreadCountReceiver: BroadcastReceiver? = null
    private var badegView: View? = null

    private var mLocationClient: AMapLocationClient? = null
    private var mLocationOption: AMapLocationClientOption? = null

    var inviteCustodyBean:InviteCustodyBean? = null

    private val dialog by lazy {
        AppUpdateDialog(this) {
            if (it) {
                //finish()
            }
        }
    }

    val dialogInvite by lazy {
        DialogTipNew(this, "监护邀请","", "确认","取消",false,{
            inviteCustodyBean?.let {
                mViewModel.confirmInvite(it.id,"1")
            }
        }){
            inviteCustodyBean?.let {
                mViewModel.confirmInvite(it.id,"0")
            }
        }

    }

    private fun initUnreadCountReceiver() {
        unreadCountReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val unreadCount = intent.getLongExtra(Const.UNREAD_COUNT_EXTRA, 0)
//                if (unreadCount > 0) {
//                    isShowReadAllButton = true
                imunreadCount = unreadCount.toInt()
                setBadge(sysunreadCount + unreadCount.toInt())
//                } else {
//                    isShowReadAllButton = false
//                    setBadge(unreadCount)
//                }
            }
        }
        val unreadCountFilter = IntentFilter()
        unreadCountFilter.addAction(Const.CONVERSATION_UNREAD_COUNT_ACTION)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(unreadCountReceiver as BroadcastReceiver, unreadCountFilter)
    }

    private val listFragment by lazy {
        listOf(
            HealthHomeFrag(),
         //   Fragment(),
            ShopFragment(),
            DynamicManagementFrag(),
            MessageFragment(),
            MineFrag()
        )
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        super.initView()
        //在离线登录的情况下查询
        initVp2()
        initBottomNav()
        addNv()
        mViewModel.getVersionNew()
        initUnreadCountReceiver()
        JPushInterface.setBadgeNumber(this, 0)

        //请求用户设备信息
        val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else {
            MMkvHelper.getLong(Const.USER_ID).toString()


        }

        if(!TextUtils.isEmpty(userId)){
            mViewModel.getIsDemonstate()
            mViewModel.getMySetting()
          //  if (BuildConfig.isRelease) {//设置极光推送别名
                JPushInterface.setAlias(
                    this,
                    MMkvHelper.getLong(Const.USER_ID).toInt(),
                    "user_release_${MMkvHelper.getLong(Const.USER_ID)}"
                )
       //     }
        }

        mViewModel.getUserEquipmentInformationizationRequest(userId)
        mViewModel.getBanners(userId,3)




       /* if(EasyPermissions.hasPermissions(this,  Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            AmapInit.startLocation(this) {
                LogUtils.e("DynamicManagementFrag","${it.city}")
                MMkvHelper.put(Const.LONGITUDE,it.longitude)
                MMkvHelper.put(Const.LATITUDE,it.latitude)
                MMkvHelper.put(Const.PROVINCE,it.province)
                MMkvHelper.put(Const.CITY,it.city)
                MMkvHelper.put(Const.DISTRICT,it.district)
          //      mViewModel.getWeather()

            }
        }else{
            EasyPermissions.requestPermissions(this,"申请定位权限",
                0x00022,
                Manifest.permission.ACCESS_COARSE_LOCATION,  Manifest.permission.ACCESS_FINE_LOCATION);
        }*/
     //   mViewModel.getBindList(BaseDeviceBindListAct.DeviceType.BODYFAT.type)
    }

  /*  private fun initBleSDK() {
        BlueUtil.getBlueManage().setDebug(BuildConfig.isRelease)
        BlueUtil.getBlueManage()
            .init(
                this,
                "",
                "",
                null,
                this
            )
    }*/

    fun initVp2() {
        binding.mVp2.adapter = VpAdapter(listFragment, this)
        binding.mVp2.isUserInputEnabled = false
        binding.mVp2.offscreenPageLimit = 2
//        binding.mVp2.currentItem = 0
    }

    fun initBottomNav() {
        binding.mBottom.itemIconTintList = null  //使用自己的图片切换
        binding.mBottom.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.nav_health -> {
                    binding.mVp2.setCurrentItem(0, false)
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.nav_server -> {
                    binding.mVp2.setCurrentItem(1, false)
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.nav_dynamic_management -> {
                    if (MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                    }else{
                        binding.mVp2.setCurrentItem(2, false)
                        return@setOnNavigationItemSelectedListener true
                    }

                }

                R.id.nav_message -> {
                    binding.mVp2.setCurrentItem(3, false)
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.nav_mine -> {
                    binding.mVp2.setCurrentItem(4, false)
                    return@setOnNavigationItemSelectedListener true
                }

            }
            false
        }

        binding.gifImageVIew.setOnClickListener {
            if (binding.mBottom.selectedItemId == R.id.nav_dynamic_management) return@setOnClickListener
            binding.mBottom.selectedItemId = R.id.nav_dynamic_management
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }

    public fun setCurrentTab(position: Int) {
        binding.mVp2.setCurrentItem(position, false)
        binding.mBottom.selectedItemId = R.id.nav_message
    }

    var nowTime = 0L
    var oldTime = 0L
    override fun onBackPressed() {
        nowTime = System.currentTimeMillis()
        if (oldTime == 0L) {
            oldTime = nowTime
            CommonToastUtils.showToast("再按一次退出程序")
        } else if (nowTime - oldTime > 2000) {
            oldTime = nowTime
            CommonToastUtils.showToast("再按一次退出程序")
        } else {
            mainScope.launch {
                delay(100)
                RxActivityTool.AppExit(applicationContext)
            }
            super.onBackPressed()
        }
    }

    override fun liveObserver() {
        mViewModel.saveSuccess.observe(this) {
        }

        //个人设置信息获取
        mViewModel.settingLive.observe(this) {
            if (null == it.data) return@observe
            it.data.let { settingBean ->

                if (BuildConfig.isRelease) {//设置极光推送别名
                    JPushInterface.setAlias(
                       this,
                        settingBean.user.id.toInt(),
                        "user_release_${settingBean.user.id}"
                    )
                }
                Const.mainLiveData.value = settingBean
//                binding.mNoNetwork.root.visibility = View.GONE
            }
        }

/*        mViewModel.boundDevices.observe(this) {
            if (it.code != 0) return@observe
            val data = it.data
            if (data.isNotEmpty()) {
                if (checkBlueConnectPermission(this)) {
                    //体脂秤sdk初始化
                   // initBleSDK()
                    if (BlueUtil.getBlueManage().isInitialized) {
                        it.data.forEach { bleData ->
                            BlueUtil.getBlueManage().addBondedMac(bleData.mac)
                        }
                        BlueUtil.getBlueManage().connectBondedDevices()
                    }
                }
            }
        }*/

        mViewModel.updateLive.observe(this) {
            if (!it.data.url.isNullOrEmpty()) {
                dialog.showUploadDialog(it.data.url!!, it.data.log,it.data.name ,it.data.isupdate) { show ->
                    isDialogShow = show
                }
            }
        }

        mViewModel.isDemonstrateData.observe(this){
            isDemonstrate = it.data == "1"
        }

        mViewModel.findInfoLiveData.observe(this){
            if (it.data != null){
                inviteCustodyBean = it.data
                dialogInvite.setContentNew("${CommonUtils.replaceMiddleNumber(it.data.phone)}用户邀请您成为 监护人")
                dialogInvite.show()
            }

        }

        mViewModel.bannerLive.observe(this){

            it[3]?.let {
                if(it != null && it.size > 0){
                    DialogActivities(this,it[0]).show()
                }
            }

        }

        //未读消息操作
       /* mViewModel.countLive.observe(this) {
            setUnreadcount(it.data.count)
            EventBus.getDefault()
                .post(ShowSystemMessageEvent(it.data.msg, it.data.time, it.data.count))
            if (it.data.count > 0) {
                RxSPTool.putString(this, Const.UnReadSysMessageContentKey, it.data.msg)
                RxSPTool.putString(this, Const.UnReadSysMessageTimeKey, it.data.time)
            }
        }*/

        /*mViewModel.getImUserSig.observe(this) {
            Log.e("simon", it.data)
            TUILogin.login(
                applicationContext,
                ,
                it.paramsData,
                it.data,
                object : TUICallback() {
                    override fun onSuccess() {
                        Log.e("simon", "登陆成功")
                        TUIChatConfigs.getConfigs().generalConfig.isEnableWelcomeCustomMessage =
                            false
                        handleOfflinePush(intent)
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                    }
                })
        }*/

        //获取用户设备信息网络请求返回
        mViewModel.getUserEquipmentInformationization.observe(this) {
            if (it.code != 0) {
                CommonToastUtils.showLoserToast("获取设备信息失败")
            }
            when (it.data.bindStatus) {
                0 -> {
                    binding.mVp2.currentItem = 0
                    binding.mBottom.selectedItemId = R.id.nav_health
                }

                1 -> {
                    binding.mVp2.currentItem = 2
                    binding.mBottom.selectedItemId = R.id.nav_dynamic_management
                }

                else -> {
                    binding.mVp2.currentItem = 0
                    binding.mBottom.selectedItemId = R.id.nav_health
                }
            }
        }
    }

    private fun addNv() {
        val menuView = binding.mBottom.getChildAt(0) as BottomNavigationMenuView
        //这里就是获取所添加的每一个Tab(或者叫menu)，
        val tab = menuView.getChildAt(3) as BottomNavigationItemView
        //加载我们的角标View，新创建的一个布局
        badegView = LayoutInflater.from(this).inflate(R.layout.item_msg_count, tab, true)

    }

    fun setUnreadcount(data: Int) {
        sysunreadCount = data
        setBadge(imunreadCount + data)
    }

    private fun setBadge(num: Int) {
        badegView?.let {
            var tv = it.findViewById<TextView>(R.id.mBadge)
            var carrdView = it.findViewById<CardView>(R.id.mCard)
            if (num > 0) {
                tv.visibility = View.VISIBLE
                tv.text = if (num > 99) "99+" else "$num"
                tv.post {
                    val layoutParams = tv.layoutParams as ViewGroup.LayoutParams
                    val text = tv.text.toString()
                    carrdView.radius = tv.height / 2f
                    var textWidth = tv.paint.measureText(text)
                    if (tv.height >= textWidth) {   //等宽高的圆形
                        layoutParams.width = tv.height

                    } else {  //宽高不等 将宽度两边加10
                        layoutParams.width = textWidth.toInt() + 20
                    }
                    tv.layoutParams = layoutParams
                }
            } else {
                tv.visibility = View.GONE
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun reveiveMsg(event: MqttReceive) {
    }

    override fun accept(abstractMeasureData: AbstractMeasureData) {
        if (abstractMeasureData is WeightMeasureData) {
            if (!abstractMeasureData.isProcessingData) {
                Log.i("LS-Bluetooth", "收到测量过程数据:${JSON.toJSONString(abstractMeasureData)}")
                val deviceInfo = abstractMeasureData.deviceInfo
                mViewModel.saveWeight(
                    abstractMeasureData.weight,
                    abstractMeasureData.resistance50K,
                    deviceInfo.sn
                )
                EventBus.getDefault()
                    .post(MeasureWeightEvent(JSON.toJSONString(abstractMeasureData)))
                return
            }
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        AmapInit.stopLocation()
  //      BlueUtil.getBlueManage().releaseResource()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun bindDevSuccess(event: BindDevEvent){
           mViewModel.getMySetting()
        mViewModel.getIsDemonstate()

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshUI(event: MyInfoEvent){
        mViewModel.getMySetting()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginOrRegisterSuccess(event: LoginOrRegisterEvent){
        mViewModel.getMySetting()
        mViewModel.getIsDemonstate()
    }

}