package com.zj365.dc.fragment

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.view.View
import androidx.annotation.RequiresApi
import cn.jpush.android.api.JPushInterface
import com.xty.base.dialog.AppUpdateDialog
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.AddSuccessEvent
import com.xty.common.event.BindDevEvent
import com.xty.common.event.LoginOrRegisterEvent
import com.xty.common.event.LoginOutEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.common.util.PermissionUtils
import com.xty.common.xqr_code.XQRCodeAct
import com.xty.network.model.InviteCustodyBean

import com.xty.network.model.SettingBean
import com.xty.network.model.UserOtherInfo
import com.zj365.dc.BuildConfig
import com.zj365.dc.activity.MainActivity
import com.zj365.dc.databinding.FragMineBinding
import com.zj365.health.vm.ReportVm
import com.zj365.health.weight.DialogTip
import com.zj365.health.weight.DialogTipNew
import com.zj365.mime.act.DevInfoAct
import com.zj365.mime.vm.SettingVm
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pub.devrel.easypermissions.EasyPermissions

/**
** 我的
*/


class MineFrag : BaseVmFrag<SettingVm>() , EasyPermissions.PermissionCallbacks{

    private val binding by lazy { FragMineBinding.inflate(layoutInflater) }

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

    var isDemonstrate: Boolean = false

    var otherInfo: UserOtherInfo? = null
    override fun setLayout(): View = binding.root

    private val defaultIcon by lazy {
        arrayOf(
            R.mipmap.icon_default_avator,
            R.mipmap.icon_default_avator
        )
    }
    var user: SettingBean.User? = null
    private var showIdInfo = "" //需要显示的信息的id

    var inviteCustodyBean: InviteCustodyBean? = null

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

    }

    override fun setViewModel() = SettingVm()

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        super.initView()
//        statusBar(binding.statusBar)
        showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else {
            MMkvHelper.getLong(Const.USER_ID).toString()
        }

        isDemonstrate = (requireActivity() as MainActivity).isDemonstrate

        //刷新注册
        refresh()

        binding.mNoNetwork.mRefreshBtn.isSelected = true
        binding.mNoNetwork.mRefreshBtn.setOnClickListener {
            mViewModel.getMySetting()
            mViewModel.getAllInfo(showIdInfo,false)

            mViewModel.searchInviteInfo()
        }

        binding.clInfo.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else{
                RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
            }
        }

        binding.mllIntegral.setOnClickListener {  //积分
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else{
                CommonToastUtils.showToast("敬请期待")
            }

        }

        binding.mllCoupon.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString(
                    "web_site_url",
                    "${BuildConfig.h5url}pages/index/index?pageId=coupon"
                )
                RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
//                CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.mllWallet.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString(
                    "web_site_url",
                    "${BuildConfig.h5url}pages/index/index?pageId=wallet"
                )
                RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
       //         CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llEarlyWarningOfDisease.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                if (isDemonstrate) {
                    bundle.clear()
                    bundle.putString("id", showIdInfo)
                    bundle.putInt("page", 1)
                    RouteManager.goAct(ARouterUrl.WARRING, bundle)
                    return@setOnClickListener
                }


                mViewModel.allData.value?.apply {
                    data.apply {
                        if (adorn.wearCount > 29 && adorn.activeWear > 14) {
                            onEventObject(requireContext(), UmengEventId.Health30Day)
                            bundle.clear()
                            bundle.putString("id", showIdInfo)
                            bundle.putInt("page", 1)
                            RouteManager.goAct(ARouterUrl.WARRING, bundle)
                        } else {
                            onEventObject(
                                requireContext(),
                                UmengEventId.Health30Day,
                                "佩戴未满30天或活跃天数未满15天。"
                            )
                            CommonToastUtils.showToast("尊敬的用户您好，该功能需要佩戴30天且活跃佩戴15天查看，请坚持佩戴且每日同步数据！")
                        }
                    }
                }
            }
        }

        binding.llRiskAssessment.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString("id", showIdInfo)
                RouteManager.goAct(ARouterUrl.SUBMIT_REPORTMain, bundle)
            }
        }

        binding.mllMember.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.mAppreciation.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString(
                    "web_site_url",
                    "${BuildConfig.h5url}pages/index/index?pageId=appreciation"
                )
                RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
//                CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llHealthRecord.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                RouteManager.goAct(ARouterUrl.FAMILY_RECORD_ACT)

//                CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llHealthMonitor.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
             //   CommonToastUtils.showToast("敬请期待")

                bundle.clear()
                bundle.putInt("page", 0)
                bundle.putBoolean("isDemonstrate", (requireActivity() as MainActivity).isDemonstrate)

                Const.functionListDate.value?.let {
                    if(it.size > 0){
                        bundle.putParcelableArrayList("functionList",it)
                    }
                }

                val id = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                    ""
                } else {
                    MMkvHelper.getLong(Const.USER_ID).toString()
                }
                bundle.putString("id", id)
                bundle.putString("sex", CommonUtils.getMyUserInfo()?.sex.toString())

                RouteManager.goAct(ARouterUrl.HEALTHMAIN, bundle)
            }
        }

        binding.llHealthDaily.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {

                bundle.clear()
                bundle.putString("id", showIdInfo)
                bundle.putSerializable("index", ReportVm.ReportInfoType.Day)
                bundle.putBoolean("isDemonstrate", isDemonstrate)
                bundle.putInt("pageType", 0)
                bundle.putString("titleName", "日报")
                Const.functionListDate.value?.let {
                    if(it.size > 0){
                        bundle.putParcelableArrayList("functionList",it)
                    }
                }
                RouteManager.goAct(ARouterUrl.HEALTH_SKY_HOUR_REPORT, bundle)
            }
        }
        binding.llStartBs.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                otherInfo?.let {
                    if (!TextUtils.isEmpty(it.start_business)){
                        bundle.clear()
                        bundle.putString(
                            "web_site_url",
                            "${it.start_business}"
                        )
                        RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
                    }else{
                        CommonToastUtils.showToast("敬请期待")

                    }
                }?:{
                    CommonToastUtils.showToast("敬请期待")

                }
            }
        }

        binding.llDailyPoster.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                otherInfo?.let {
                    if (!TextUtils.isEmpty(it.placard)){
                        bundle.clear()
                        bundle.putString(
                            "web_site_url",
                            "${it.placard}"
                        )
                        RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
                    }else{
                        CommonToastUtils.showToast("敬请期待")

                    }
                }?:{
                    CommonToastUtils.showToast("敬请期待")

                }

            }
        }


        binding.llAboutUs.setOnClickListener {
            RouteManager.goAct(ARouterUrl.ABOUT)
        }

        binding.llDataComparsion.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString("id", user?.id)
                Const.functionListDate.value?.let {
                    if(it.size > 0){
                        bundle.putParcelableArrayList("functionList",it)
                    }
                }

                RouteManager.goAct(ARouterUrl.COMPARE_PAGE_DATA_ACT, bundle)
            }
        }

        binding.llSetting.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putSerializable("user", user)
                bundle.putBoolean(
                    "isDemonstrate",
                    (requireActivity() as MainActivity).isDemonstrate
                )
                RouteManager.goAct(ARouterUrl.SETTING, bundle)
            }
        }

        binding.llEnterpriseData.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                RouteManager.goAct(ARouterUrl.ENTERPRISE_INFO)
//                CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llShippingAddress.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                bundle.clear()
                bundle.putString(
                    "web_site_url",
                    "${BuildConfig.h5url}pages/index/index?pageId=address"
                )
                RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
              //  CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llOperationGuide.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                otherInfo?.let {
                    if (!TextUtils.isEmpty(it.operation_guide)){
                        bundle.clear()
                        bundle.putString("title", "操作手册")
                        bundle.putBoolean("isAgree", false)
                        bundle.putString("url", "${it.operation_guide}")
                        RouteManager.goAct(ARouterUrl.AGREEMNT_READ_WEB_ACT, bundle)
                    }else{
                        CommonToastUtils.showToast("敬请期待")

                    }
                }?:{
                    CommonToastUtils.showToast("敬请期待")

                }

            }
        }

        binding.llOrder.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                RouteManager.goAct(ARouterUrl.SHOP_ORDER_LIST_ACT)
                //CommonToastUtils.showToast("敬请期待")
            }
        }

        binding.llFamilyHealth.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                RouteManager.goAct(ARouterUrl.FAMILY_HEALTH_ACT)
            }
        }
        binding.llWearableDevice.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                CommonUtils.getMyUserInfo()?.let {
                    if (it.watchName == null) {
                        RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
                    } else {
                        //设备信息
                        //   unBindDialog.show()
                        bundle.clear()
                        bundle.putSerializable("user", it)
                        RouteManager.goAct(ARouterUrl.DEV_INFO, bundle)
                    }
                }
            }
        }
        binding.llDataComparsion.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                goComparePage()
            }
        }

        binding.llUpGraded.setOnClickListener {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                mViewModel.getVersionNew(BuildConfig.VERSION_CODE)
            }
        }

        binding.llCustomerService.setOnClickListener {

            if(EasyPermissions.hasPermissions(requireContext(),
                    Manifest.permission.CALL_PHONE)){
                startActivity(Intent(Intent.ACTION_CALL, Uri.parse("tel:4000063365")))
            }else{
                EasyPermissions.requestPermissions(this,"",
                    0x00011,
                    Manifest.permission.CALL_PHONE)
            }
        }
    }

    private fun refresh() {
        refresh.setRefresh(binding.mRefresh) {
            mViewModel.getMySetting()
            mViewModel.getUserOtherInfo()
            mViewModel.getAllInfo(showIdInfo,false)
            mViewModel.searchInviteInfo()
        }
    }

    override fun onResume() {
        super.onResume()
        if (!TextUtils.isEmpty(showIdInfo)){
            mViewModel.getMySetting()
            mViewModel.getAllInfo(showIdInfo,false)
            mViewModel.searchInviteInfo()

            mViewModel.getUserOtherInfo()
        }

    }

    override fun observer() {
       /* mViewModel.familyLive.observe(this) {
            binding.mFamily.text = it.data.size.toString()
        }*/
        mViewModel.useOtherInfoLiveData.observe(this){
            otherInfo = it.data
            binding.tvMemberValidity.text ="有效期至：${it.data.vip_end_time}"
            binding.mCoupon.text = "${it.data.coupons_count}"
            binding.mTvWallet.text = "${it.data.money}"
            binding.tvOrder.text = "${it.data.order_count}"

            if(TextUtils.isEmpty(it.data.start_business)){
                binding.llStartBs.visibility = View.GONE
            }else{
                binding.llStartBs.visibility = View.VISIBLE
            }

            if(TextUtils.isEmpty(it.data.placard)){
                binding.llDailyPoster.visibility = View.GONE
            }else{
                binding.llDailyPoster.visibility = View.VISIBLE
            }


        }
        mViewModel.scoreLive.observe(this) {
            binding.mIntegral.text = (if (it.data.num.isNullOrEmpty()) "0" else it.data.num!!)
        }

        mViewModel.updateLive.observe(this) {
            if (!it.data.url.isNullOrEmpty()) {
                dialog.showUploadDialog(it.data.url!!, it.data.log,it.data.name ,it.data.isupdate) { show ->
                }
            }else{
                CommonToastUtils.showSucceedToast("已经是最新版本")
            }
        }

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

        }


        Const.mainLiveData.observe(this) {
            if (null == it) {
                return@observe
            }
            user = it.user
            binding.mName.text = it.user.name
            binding.mPhone.text = "${it.user.phone}"
//            binding.mDk.text = it.clock.toString()
//            binding.mLevel.text = it.grade
            if (it.user.avatarUrl.isNullOrEmpty()) {
                binding.mImage.setImageResource(defaultIcon[if (it.user.sex - 1 < 0) 0 else it.user.sex - 1])
            } else {
                binding.mImage.setImageUser(
                    requireContext(),
                    it.user.avatarUrl,
                    it.user.sex.toString()
                )
                Const.CHAT_IMAGE = it.user.avatarUrl
            }


        }

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

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


    }

    private fun goComparePage() {
        bundle.clear()
        bundle.putString("id", user?.id)
        RouteManager.goAct(ARouterUrl.COMPARE_PAGE_DATA_ACT, bundle)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginOrRegisterSuccess(event: LoginOrRegisterEvent){
        showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else {
            MMkvHelper.getLong(Const.USER_ID).toString()
        }
  //      mViewModel.getMySetting()
//        mViewModel.getScore(1)
        mViewModel.searchInviteInfo()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginOutUIChange(event: LoginOutEvent){
        refreshLogoutUI()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addSuccess(event: AddSuccessEvent){
    //    mViewModel.getMySetting()
        mViewModel.getAllInfo(showIdInfo,false)
//        mViewModel.getScore(1)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun bindDevSuccess(event:BindDevEvent){
    //    mViewModel.getMySetting()
        mViewModel.getAllInfo(showIdInfo,false)
//        mViewModel.getScore(1)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshUI(event: MyInfoEvent){
      //  mViewModel.getMySetting()
        mViewModel.getAllInfo(showIdInfo,false)
//        mViewModel.getScore(1)
        mViewModel.searchInviteInfo()
    }



/*** 设置消息数量*/


    private fun setBadge(num: Int) {
//        if (num > 0) {
//            binding.mCard.visibility = View.VISIBLE
//            binding.mBadge.text = if (num > 99) "99+" else "$num"
//            binding.mBadge.post {
//                val layoutParams = binding.mBadge.layoutParams as ViewGroup.LayoutParams
//                val text = binding.mBadge.text.toString()
//                binding.mCard.radius = binding.mBadge.height / 2f
//                var textWidth = binding.mBadge.paint.measureText(text)
//                if (binding.mBadge.height >= textWidth) {   //等宽高的圆形
//                    layoutParams.width = binding.mBadge.height
//
//                } else {  //宽高不等 将宽度两边加10
//                    layoutParams.width = textWidth.toInt() + 20
//                }
//                binding.mBadge.layoutParams = layoutParams
//            }
//        } else {
//            binding.mCard.visibility = View.GONE
//        }
    }

    fun refreshLogoutUI(){
        user = null
        binding.mIntegral.text = "0"
        binding.mName.text = ""
        binding.mPhone.text = ""
        binding.mImage.setImageResource(defaultIcon[0])
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        startActivity(Intent(Intent.ACTION_CALL, Uri.parse("tel:4000063365")))
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
    }

}
