package com.zj365.health.act.healthrecord

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.core.view.get
import androidx.core.view.size
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.androidkun.xtablayout.XTabLayout
import com.xty.base.act.BaseVmAct
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.MMkvHelper
import com.xty.common.R
import com.xty.common.UmengEventId
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.onEventObject
import com.xty.common.setImageUser
import com.xty.common.weight.HealthBodyView
import com.zj365.health.BuildConfig
import com.zj365.health.adapter.familyhealth.HealthFamilyTargetAdapter
import com.zj365.health.databinding.ActHealthRecordMainBinding
import com.zj365.health.model.MyReportBean
import com.zj365.health.vm.HealthRecordMainVm
import com.zj365.health.vm.ReportVm
import com.zj365.health.weight.HealthSurveyView
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Route(path = ARouterUrl.FAMILY_RECORD_ACT)
class HealthRecordMainAct : BaseVmAct<HealthRecordMainVm>() {

    val binding by lazy { ActHealthRecordMainBinding.inflate(layoutInflater) }

    val mAdapter by lazy { HealthFamilyTargetAdapter() }


    private val mTitles = mutableListOf<String>()

    private var isSelectTable = false
    private var isScrollTable = false
    private var launch: Job? = null


    override fun liveObserver() {

        mViewModel.balanceDietBeanLiveData.observe(this){
            binding.tvDietCalorie.text = "${it.data.heat_val}"
            binding.proCho.progress = it.data.cho_percent.toInt()
            binding.proFat.progress = it.data.fat_percent
            binding.proProtein.progress = it.data.protein_percent
            binding.tvProteinPro.text = "${it.data.protein_percent}%"
            binding.tvFatPro.text = "${it.data.fat_percent}%"
            binding.tvChoPro.text =  "${it.data.cho_percent}%"
        }

        mViewModel.healthArchiveLiveData.observe(this){
            binding.tvBmi.text = "${it.data.bmiInfo.bmi}"
            binding.tvBmiDesc.text = it.data.bmiInfo.levelName
            if (it.data.bmiInfo.levelName.equals("理想")){
                binding.tvBmiDesc.setTextColor(Color.parseColor("#02C191"))
            }
            binding.tvBmr.text = "${it.data.bmr}"
            mAdapter.setNewInstance(it.data.healData)
        }

    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text ="健康档案"
        binding.title.mIvBack.setOnClickListener {
            finish()
        }

        mViewModel.getBalanceDiet()

        mViewModel.getHealthArchive()

        initTab()
        initSurvey()
        initAdapter()
        initClickListener()

        Const.mainLiveData.value?.let {
            binding.tvName.text = it.user.name
            if (it.user.avatarUrl.isNullOrEmpty()) {
                binding.imgAvatar.setImageResource(R.mipmap.icon_default_avator)
            } else {
                binding.imgAvatar.setImageUser(
                    this,
                    it.user.avatarUrl,
                    it.user.sex.toString()
                )
            }

        }
    }

    fun initClickListener(){
        binding.llInquiryRecord.setOnClickListener {

        }

        binding.tvDairyRecords.setOnClickListener {
            bundle.clear()
            bundle.putString(
                "web_site_url",
                "${BuildConfig.h5url}pages/index/index?pageId=diary"
            )
            RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
        }

        binding.llHealthWeekRecord.setOnClickListener {
            bundle.clear()
           var  showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                ""
            } else {
                MMkvHelper.getLong(Const.USER_ID).toString()
            }
            bundle.putString("id", showIdInfo)
            bundle.putSerializable("index", ReportVm.ReportInfoType.Week)
            bundle.putBoolean("isDemonstrate", Const.isDemonstrate)
            bundle.putString("titleName", "周报")
            Const.functionListDate.value?.let {
                if(it.size > 0){
                    bundle.putParcelableArrayList("functionList",it)
                }
            }
            RouteManager.goAct(ARouterUrl.HEALTH_WEEK_MONTH_HOUR_REPORT, bundle)
        }

        binding.llReportRecord.setOnClickListener {
            RouteManager.goAct(ARouterUrl.FAMILY_REPORT_LIST_ACT)
        }

        binding.tvCompleteInfo.setOnClickListener {
            RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
        }
    }

    fun initSurvey(){
        var surveyList = ArrayList<String>()

        surveyList.add("免疫系统")
        surveyList.add("神经系统")
        surveyList.add("内分泌系统")
        surveyList.add("泌尿系统")
        surveyList.add("生殖系统")
        surveyList.add("运动系统")
        surveyList.add("心脑血管")
        surveyList.add("消化系统")
        surveyList.add("呼吸系统")

        binding.clBody.surveyView.setMenuItemTexts(surveyList)

        binding.clBody.surveyView.setOnClicklisteners(object : HealthSurveyView.onItemClicked{
            override fun onPositionClicked(postion: Int) {

            }
        })
    }

    fun initTab(){
        mTitles.add("自检自测")
        mTitles.add("饮食日记")
        mTitles.add("健康监测")
        mTitles.add("健康记录")

        //设置tab
        mTitles.forEach { tabData ->
            val tab = binding.xTablayout.newTab()
            tab.text = tabData
            binding.xTablayout.addTab(tab)
        }

        binding.xTablayout.setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: XTabLayout.Tab) {

                if (!isScrollTable) {
                    isSelectTable = true
                    if (launch != null) {
                        launch?.cancel()
                    }
                    when (mTitles[tab.position]) {
                        "自检自测" -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.clSelfTest.top
                            )
                        }

                        "饮食日记" -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.clFoodDiary.top
                            )
                        }

                        "健康监测" -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.clHealthMonitoring.top
                            )
                        }


                        "健康记录" -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.clHealthRecording.top
                            )
                        }
                    }

                    launch = GlobalScope.launch {
                        delay(1000) // 延迟一秒
                        // 在这里执行你的操作
                        isSelectTable = false
                    }
                }
            }

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

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

        })

        binding.scrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
            if (mTitles.size > 0) {
                if (!isSelectTable) {
                    isScrollTable = true
                    val selectedTabPosition = binding.xTablayout.selectedTabPosition
                    if (scrollY >= binding.clHealthRecording.top) {
                        if (selectedTabPosition != mTitles.size - 1) {
                            binding.xTablayout.getTabAt(mTitles.size - 1)?.select()
                        }
                    } else if (scrollY >= binding.clHealthMonitoring.top) {
                        if (selectedTabPosition != mTitles.size - 2) {
                            binding.xTablayout.getTabAt(mTitles.size - 2)?.select()
                        }
                    } else if (scrollY >= binding.clFoodDiary.top) {
                        if (selectedTabPosition != mTitles.size - 3) {
                            binding.xTablayout.getTabAt(mTitles.size - 3)?.select()
                        }
                    } else if (scrollY >= binding.clSelfTest.top) {
                        if (selectedTabPosition != 0) {
                            binding.xTablayout.getTabAt(0)?.select()
                        }
                    } else {
                        if (selectedTabPosition != 0) {
                            binding.xTablayout.getTabAt(0)?.select()
                            binding.xTablayout.setScrollPosition(0, 0F, true)
                        }
                    }
                    isScrollTable = false
                }
            }
        })
    }

    fun initAdapter (){
        binding.recycler.adapter = mAdapter
        binding.recycler.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
    }

    override fun setLayout() = binding.root
}