package com.zj365.health.act

import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
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.chad.library.adapter.base.entity.MultiItemEntity
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.Health24HourStatusEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.adapter.Health24HourAdapter
import com.zj365.health.databinding.ActHealth24hourReportBinding
import com.zj365.health.model.ReportMultiItemEntity
import com.zj365.health.vm.ReportVm
import com.zj365.health.weight.DialogTip
import com.zj365.health.weight.HealthDialog
import com.xty.network.model.ReportBean
import org.greenrobot.eventbus.EventBus

/**
 * 24小时评估报告
 */
@Route(path = ARouterUrl.HEALTH_24HOUR_REPORT)
class Health24HourReportAct : BaseVmAct<ReportVm>() {
    val dialogBind by lazy {
        DialogTip(this, "需绑定中健三六五健康手表，才能查看","去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }
    private var isDemonstrate: Boolean = false
    val binding by lazy { ActHealth24hourReportBinding.inflate(layoutInflater) }

    private val tab by lazy { resources.getStringArray(R.array.status_title) }

    private val mAdapter by lazy { Health24HourAdapter<MultiItemEntity>() }

    val tipDialog by lazy {
        //-1 建模中 0数据不足 1健康 2亚健康 3疾病
        val title = when (healthStatus) {
            0 -> {
                getString(R.string.tip_nodata_data)
            }
            1 -> {
                getString(R.string.tip_health_data)
            }
            2 -> {
                getString(R.string.tip_subhealth_data)
            }
            3 -> {
                getString(R.string.tip_disease_data)
            }
            else -> {
                getString(R.string.tip_nodata_data)
            }
        }
        HealthDialog(this, true, title) {
        }
    }

    var id = ""
    var openId = ""
    var reportBean: ReportBean? = null
    var listAllData = mutableListOf<MultiItemEntity>()
    var reportCreateTime = ""//报告生成时间

    var healthStatus = -2

    override fun setLayout() = binding.root

    var nowPosition = 0

    override fun initData() {
        super.initData()
        intent.extras?.let {
            isDemonstrate = intent.extras!!.getBoolean("isDemonstrate",false)
            if (!it.getString("id").isNullOrEmpty()){
                id = it.getString("id").toString()
            }
            if (!it.getString("openId").isNullOrEmpty()){
                openId = it.getString("openId").toString()
            }
            if (it.getSerializable("reportBean")!=null){
                val serializable =it.getSerializable("reportBean")
                reportBean = if (null == serializable) null else serializable as ReportBean
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener {
            back2LastPage()
        }
        if (isDemonstrate){
            binding.title.mTvTitle.text = getString(R.string.health_24hour_report_de)
        }else{
            binding.title.mTvTitle.text = getString(R.string.health_24hour_report)
        }
        binding.title.mIvReight.apply {
            visibility = View.VISIBLE
            this.setImageResource(R.mipmap.icon_share)
            this.setOnClickListener {
                if (isDemonstrate){
                    dialogBind.show()
                    return@setOnClickListener
                }
                share()
            }
        }

        initRecycle()
        initTab(tab.toMutableList())

        if (isDemonstrate){
            binding.mGuid.text = "退出演示模式"
        }
        binding.mGuid.setOnClickListener {
            if (isDemonstrate){
                finish()
                return@setOnClickListener
            }
            bundle.clear()
            bundle.putString("id", id)
            bundle.putSerializable("reportBean", reportBean)
            RouteManager.goAct(ARouterUrl.HEALTH_PROP, bundle)
        }

        if (null == reportBean) {
            mViewModel.get24HourReportInfo(id,isDemonstrate)
        } else {
            if (reportBean?.user?.id?.equals(CommonUtils.getMyUserId()) == true) {//如果id是自己获取和当前获取的id一致则直接填充数据
                reportBean?.let { updateReportInfo(it) }
            } else {
                mViewModel.get24HourReportInfo(id, isDemonstrate)
            }
        }
        onEventObject(baseContext, UmengEventId.Health24HourReport)
    }

    private fun initRecycle() {
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.mTvStatus,R.id.tvHint)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            tipDialog.show()
        }

        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()
            }
        })

    }


    private fun initTab(tabList: MutableList<String>) {
        tabList.forEach {
            var tab = binding.xTablayout.newTab()
            tab.text = it
            binding.xTablayout.addTab(tab)
        }

        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 onBackPressed() {
        back2LastPage()
    }

    /**
     * 返回至上一页面
     */
    private fun back2LastPage() {
        EventBus.getDefault().post(Health24HourStatusEvent(healthStatus))
        finish()
    }


    override fun liveObserver() {
        mViewModel.infoLive.observe(this) {
            if (null == it) {
                CommonToastUtils.showToast("请求异常，请重试。。。")
                LogUtils.e("请求返回异常，没得数据。。。")
                return@observe
            }

            it.data?.let {
                reportBean = it
                updateReportInfo(it)
            }
        }
    }

    private fun updateReportInfo(reportBean: ReportBean) {
        reportCreateTime = reportBean.healthy.createTime
        healthStatus = if (reportBean.healthy == null) -2 else reportBean.healthy.result

        listAllData.add(ReportMultiItemEntity(0).apply { this.bean = reportBean })
        listAllData.add(ReportMultiItemEntity(1).apply { this.bean = reportBean })

        listAllData.add(ReportMultiItemEntity(2).apply { this.bean = reportBean })
        listAllData.add(ReportMultiItemEntity(3).apply { this.bean = reportBean })
        mAdapter.setNewInstance(listAllData)
    }

    fun share() {
        CommonUtils.getMyUserInfo()?.apply {
            var aesId = AESCrypt.encrypt("${id}")
            var subtitle = "${name}的24小时健康分析数据"
            var url = "${BuildConfig.image_prefix}/shareApi/reportDaily/$aesId/${reportCreateTime}"
            WxUtils.shareWebPage("24小时健康分析报告分享", subtitle, baseContext, url)
        }
    }
}