package com.zj365.health.act

import android.content.res.AssetManager
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.androidkun.xtablayout.XTabLayout
import com.gyf.immersionbar.ImmersionBar
import com.xty.base.act.BaseVmAct
import com.xty.base.act.IBaseAct
import com.xty.base.vm.BaseVm
import com.xty.base.vp2.VpAdapter
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.util.DeviceFunctionUtils
import com.xty.common.weight.tablayout.listener.CustomTabEntity
import com.xty.network.model.DeviceFunctionBean
import com.zj365.health.R
import com.zj365.health.databinding.ActHealthMainBinding
import com.zj365.health.fragment.BreathCompareDataFrag
import com.zj365.health.fragment.bloodlipid.BloodFatFrag
import com.zj365.health.fragment.BreathFrag
import com.zj365.health.fragment.SleepCompareDataFrag
import com.zj365.health.weight.DialogTip
import com.zj365.health.fragment.SleepFrag
import com.zj365.health.fragment.TemFrag
import com.zj365.health.fragment.TempCompareDataFrag
import com.zj365.health.fragment.UricAcidCompareDataFrag
import com.zj365.health.fragment.UricAcidFrag
import com.zj365.health.fragment.XYangCompareDataFrag
import com.zj365.health.fragment.XdFrag
import com.zj365.health.fragment.XinlvFrag
import com.zj365.health.fragment.XlCompareDataFrag
import com.zj365.health.fragment.XueTangCompareDataFrag
import com.zj365.health.fragment.XueTangFrag
import com.zj365.health.fragment.XueYaCompareDataFrag
import com.zj365.health.fragment.XueyaFrag
import com.zj365.health.fragment.XueyangFrag
import com.zj365.health.fragment.bloodlipid.BloodFatCompareDataFrag
import com.zj365.health.vm.HealthMainVm

/**
 * 健康监测 详情
 */
@Route(path = ARouterUrl.HEALTHMAIN)
class HealthMainAct : BaseVmAct<HealthMainVm>() {
    var isDemonstrate: Boolean = false
    var page = 0
    val binding by lazy { ActHealthMainBinding.inflate(layoutInflater) }
    var listFragment = mutableListOf<Fragment>()
   // var tabName = arrayOf<Int>()
    var id = ""
    var sex = "1"
    var functionType:String = ""
    var functionList = ArrayList<DeviceFunctionBean>()
    val dialogBind by lazy {
        DialogTip(this, "需绑定中健三六五健康手表，才能查看", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }

    override fun setLayout(): View = binding.root
    override fun initData() {
        super.initData()
      //  page = intent.extras!!.getInt("page")
        functionType = intent.extras!!.getString("functionType").toString()
        isDemonstrate = intent.extras!!.getBoolean("isDemonstrate", false)
        if(intent.extras!!.containsKey("functionList")){
            functionList = intent.extras!!.getParcelableArrayList<DeviceFunctionBean>("functionList")!!
        }
        if (intent.extras!!.containsKey("id")) {
            id = intent.extras!!.getString("id").toString()
        }
        if (intent.extras!!.containsKey("sex")) {
            sex = intent.extras!!.getString("sex").toString()
        }
    }

    override fun initView() {
        super.initView()

        val deviceType = MMkvHelper.getString(Const.DEVICE_TYPE)
        if(functionList.size == 0){
            mViewModel.getDeviceFunctionList(id)
        }else{
            initTab(functionList)
            initVp2(functionList)
        }
        /*tabName =  arrayOf(
            R.string.info_1, R.string.info_3, R.string.info_7,
            R.string.info_4, R.string.info_6, R.string.info_2,
            R.string.info_8, R.string.info_11*//*, R.string.info_5,
                    R.string.info_10*//*
        )*/

        statusBar(binding.title.mView)
        initTitle()
        if (isDemonstrate) {
            binding.mSubmit.visibility = View.VISIBLE
            binding.title.mTvTitle.text = resources.getString(R.string.health_sub_demonstrate)
            binding.mSubmit.setOnClickListener { finish() }
        }
    }

    override fun liveObserver() {
        mViewModel.functionLiveData.observe(this){
            it.data.let {
                functionList.addAll(it)
                initTab(functionList)
                initVp2(functionList)
            }
        }
    }

    private fun setArgumentFrag(frag: Fragment, id: String = "", sex: String = "1"): Fragment {
        val bundle = Bundle()
        bundle.putString("id", id)
        bundle.putString("sex", sex)
        frag.arguments = bundle
        return frag
    }

    private fun initTitle() {
        binding.title.mTvTitle.text = resources.getString(R.string.health_sub)
        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }
        changeTitle(page)
    }

    //设置tab
    private val mTabEntities: java.util.ArrayList<CustomTabEntity> = java.util.ArrayList()
    private fun initTab(functionList :MutableList<DeviceFunctionBean>) {
        binding.xTablayout.removeAllTabs()
        functionList.forEach {
            if (it.type == "step"){
                return@forEach
            }
            if (it.status == 1){
                var tab = binding.xTablayout.newTab()
                tab.text = it.name
                binding.xTablayout.addTab(tab)

                if(it.type == functionType){
                    page = tab.position
                }
            }

        }
        binding.xTablayout.setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: XTabLayout.Tab?) {
                var filed = tab!!.javaClass.getDeclaredField("mView")
                filed.isAccessible = true
                var tabView = filed.get(tab) as View
                if (tabView.isPressed) {
                    //如果是手动按压的话 跳转
                    binding.mVp2.setCurrentItem(tab!!.position, false)
                    changeTitle(tab!!.position)
                    LogUtils.d("tab: " + tab!!.position)
                }
            }

            override fun onTabUnselected(tab: XTabLayout.Tab?) {
            }

            override fun onTabReselected(tab: XTabLayout.Tab?) {
            }

        })
        binding.xTablayout.post {
            binding.xTablayout.getTabAt(page)!!.select()
        }
    }

    //设置vp2
    private fun initVp2(functionList :MutableList<DeviceFunctionBean>) {
        listFragment.clear()

        functionList.forEach {
            if (DeviceFunctionUtils.hasFunction(it,"hr")){
                listFragment.add(setArgumentFrag(XinlvFrag(), id))
            }else if(DeviceFunctionUtils.hasFunction(it,"so")){
                listFragment.add(setArgumentFrag(XueyangFrag(), id))
            }else if(DeviceFunctionUtils.hasFunction(it,"resp")){
                listFragment.add(setArgumentFrag(BreathFrag(), id))
            }else if(DeviceFunctionUtils.hasFunction(it,"temp")){
                listFragment.add(setArgumentFrag(TemFrag(), id))
            }else if(DeviceFunctionUtils.hasFunction(it,"sleep")){
                listFragment.add(setArgumentFrag(SleepFrag(), id))

            }else if(DeviceFunctionUtils.hasFunction(it,"dbp")){
                listFragment.add(setArgumentFrag(XueyaFrag(), id))

            }else if(DeviceFunctionUtils.hasFunction(it,"sugar")){
                listFragment.add(setArgumentFrag(XueTangFrag(), id))

            }else if(DeviceFunctionUtils.hasFunction(it,"uric")){
                listFragment.add(setArgumentFrag(UricAcidFrag(), id, sex))

            }else if(DeviceFunctionUtils.hasFunction(it,"bloodFat")){
                listFragment.add(setArgumentFrag(BloodFatFrag(), id))
            }
        }




        binding.mVp2.adapter = VpAdapter(listFragment, this)
        binding.mVp2.isUserInputEnabled = false
        binding.mVp2.offscreenPageLimit = 1

        binding.mVp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                //   binding.xTablayout.getTabAt(position)!!.select()
                onEventObject(
                    baseContext,
                    UmengEventId.HealthMonitor,
                    "${functionList[position].name}监测详情页"
                )
                changeTitle(position)
            }
        })
        binding.mVp2.post {
            binding.mVp2.setCurrentItem(page, false)
        }
    }

    fun changeTitle(position: Int) {
        var bg: Drawable
        var backId: Int
        var txtColInt: Int
        bg = ContextCompat.getDrawable(this, R.drawable.shape_white)!!
        txtColInt = ContextCompat.getColor(this, R.color.col_515)
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        binding.title.mIvReight.visibility = View.GONE
        var parentView = binding.title.mTvTitle.parent as View
        parentView.background = bg

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


    }

    override fun getAssets(): AssetManager {
        LogUtils.d("  失败1");
        return resources.assets;
    }

}