package com.zj365.health.act

import android.app.Service
import android.content.Intent
import android.view.View
import androidx.core.app.NotificationManagerCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.androidkun.xtablayout.XTabLayout
import com.xty.base.act.BaseVmAct
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.MusicPlayStatus
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.adapter.ProposalAdapter
import com.zj365.health.databinding.ActHealthProposalBinding
import com.zj365.health.vm.HealthProposalVm
import com.xty.network.model.MusicBean
import com.xty.network.model.ProposalBean
import com.xty.network.model.ReportBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 健康建议
 */
@Route(path = ARouterUrl.HEALTH_PROP)
class HealthProposalAct : BaseVmAct<HealthProposalVm>() {

    val binding by lazy { ActHealthProposalBinding.inflate(layoutInflater) }
    val adapter by lazy { ProposalAdapter(mutableListOf()) }
    val tab by lazy { resources.getStringArray(R.array.guid_array) }
    var nowPosition = 0
    var userId=""
    var reportBean: ReportBean? = null

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        userId = intent.extras!!.getString("id").toString()
        reportBean =
            if (null == intent.extras!!.getSerializable("reportBean")) null
            else intent.extras!!.getSerializable("reportBean") as ReportBean
    }
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvTitle.text = getString(R.string.health_jy)
        binding.title.mIvReight.apply {
            visibility = View.VISIBLE
            this.setImageResource(R.mipmap.icon_share)
            this.setOnClickListener {
                share()
            }
        }
        initRecycle()

        binding.title.mTvTitle.setOnClickListener {
            var service=RouteManager.getAny(ARouterUrl.MUSIC_SERVICE) as Service
            var intent=Intent(this,service::class.java)
            intent.putExtra("manager","")
            startService(intent)
        }

        initTab()
        initRecycle()

        if (null == reportBean) {
            mViewModel.getAllData(userId,tab)
        } else {
            reportBean?.let { assembleData(it) }
        }

    }



    private fun initRecycle() {
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = adapter


        binding.mRecycle.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                var layoutManager = recyclerView.layoutManager as LinearLayoutManager
                nowPosition = layoutManager.findFirstVisibleItemPosition()
                binding.xTablayout.getTabAt(nowPosition)!!.select()
            }
        })


    }

    override fun liveObserver() {
        mViewModel.proposalLive.observe(this) {
            updateList(it)
        }
    }

    /**
     * 组装数据传给adapter
     */
    private fun assembleData(reportBean: ReportBean){
        var listData = mutableListOf<MutableList<ProposalBean>>()

        //西医指导
        reportBean.analysis.wm?.forEach {
            val bean = ProposalBean(it.name, it.content)
            var listBean = mutableListOf<ProposalBean>()
            listBean.add(bean)
            listData.add(listBean)
        }

        //中医养生指导
        reportBean.analysis.tcm?.forEach{
            val bean = ProposalBean(it.name, it.content)
            var listBean = mutableListOf<ProposalBean>()
            listBean.add(bean)
            listData.add(listBean)
        }

        //饮食指导
        reportBean.analysis.diet?.forEach{
            val bean = ProposalBean(it.name, it.content)
            var listBean = mutableListOf<ProposalBean>()
            listBean.add(bean)
            listData.add(listBean)
        }

        //运动指导
        reportBean.analysis.exercise?.forEach{
            val bean = ProposalBean(it.name, it.content)
            var listBean = mutableListOf<ProposalBean>()
            listBean.add(bean)
            listData.add(listBean)
        }

        //睡眠方案建议
        var listBean = mutableListOf<ProposalBean>()
        listBean.add(ProposalBean("",""))
        listData.add(listBean)

        //营养处方建议
        reportBean.analysis.nutrition?.forEach{
            val bean = ProposalBean(it.name, it.content)
            var listBean = mutableListOf<ProposalBean>()
            listBean.add(bean)
            listData.add(listBean)
        }

        updateList(listData)
    }

    private fun updateList(listData: MutableList<MutableList<ProposalBean>>){
        var listMusic= mutableListOf<MusicBean>()
        mViewModel.musicLive.value?.let {
            listMusic = it
        }
        adapter.musicList=listMusic
        adapter.setNewInstance(listData)
    }

    private fun initTab() {
        val titlePosition= mutableListOf<Int>() // 标题位置

        tab.forEachIndexed { index, s ->
            var tab = binding.xTablayout.newTab()
            tab.text = s
            binding.xTablayout.addTab(tab)
            titlePosition.add(index)
        }

        adapter.list = titlePosition//设置标题位置信息

        binding.xTablayout.addOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: XTabLayout.Tab?) {
                LogUtils.d("nowPosition:$nowPosition;;;position:${tab!!.position}")
                nowPosition = tab!!.position
                //反射直接将他的底裤掏出来
                val declaredField = tab.javaClass.getDeclaredField("mView")
                declaredField.isAccessible = true
                var view = declaredField.get(tab) as View

                if (view.isPressed) {
                    (binding.mRecycle.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                        nowPosition,
                        0
                    )
                }

            }

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

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

        })
    }



    override fun onDestroy() {
        var isEnable= NotificationManagerCompat.from(this).areNotificationsEnabled()
        if(!isEnable){
            var service=RouteManager.getAny(ARouterUrl.MUSIC_SERVICE) as Service
            var intent=Intent(this,service::class.java)
            stopService(intent)
        }
        super.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun musicPlayStatus(event: MusicPlayStatus) {
        Const.musicLoading = false
        val bean = event.bean
        LogUtils.d("thread:${Thread.currentThread()}")
        adapter.mAdapter.data.forEachIndexed { index, musicBean ->
            if (musicBean.fileId == bean.fileId) {
                adapter.mAdapter.data[index].isPlayer = bean.isPlayer
                adapter.mAdapter.notifyItemChanged(index)
                return@forEachIndexed
            }
        }
    }

    fun share(){
        CommonUtils.getMyUserInfo()?.apply {
            var aesId = AESCrypt.encrypt("${id}")
            var subtitle = "${name}的健康建议"
            var url = "${BuildConfig.image_prefix}/shareApi/monitor/$aesId"
            WxUtils.shareWebPage("健康建议", subtitle, baseContext, url)
        }
    }


}