package com.zj365.health.fragment.tongue

import android.graphics.Color
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.widget.NestedScrollView
import androidx.core.widget.NestedScrollView.OnScrollChangeListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.androidkun.xtablayout.XTabLayout
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.data.RadarData
import com.github.mikephil.charting.data.RadarDataSet
import com.github.mikephil.charting.data.RadarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.utils.MPPointF
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.setImage
import com.zj365.health.R
import com.zj365.health.act.tonguediagnosis.TongueDetailActivity
import com.zj365.health.adapter.DrugCareAdapter
import com.zj365.health.adapter.EatAdapter
import com.zj365.health.adapter.XWAMAdapter
import com.zj365.health.databinding.FragmentTongueReportBinding
import com.zj365.health.vm.TongueDiagnosisVm
import com.xty.network.model.CancerGoodsBean
import com.xty.network.model.DietaryRecuperate
import com.xty.network.model.DrugHealthCare
import com.xty.network.model.MassageHealthCare
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class TongueReportFragment : BaseVmFrag<TongueDiagnosisVm>() {

    val binding by lazy { FragmentTongueReportBinding.inflate(layoutInflater) }
    override fun setViewModel() = TongueDiagnosisVm()
    override fun setLayout() = binding.root

    private var launch: Job? = null

    lateinit var bean: CancerGoodsBean

    private val mTitles = arrayOf(
        "健康状态", "舌象辨识", "健康分析","调理方案"
    )

    var isSelectTable = false
    var isScrollTable = false

    override fun initView() {
        super.initView()
        initMyView()
    }

    private fun initTab() {
        mTitles.forEach {
            var tab = binding.xTablayout.newTab()
            tab.text = it
            binding.xTablayout.addTab(tab)
        }

        binding.xTablayout.setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: XTabLayout.Tab?) {
                if (!isScrollTable) {
                    Log.e("mTag","选择的${tab?.position}")
                    isSelectTable = true
                    if (launch != null) {
                        launch?.cancel()
                    }
                    when (tab?.position) {
                        0 -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.healthState.healthStateAll.top
                            )
                        }

                        1 -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.tongueIdentify.tongueIdentifyAll.top
                            )

                        }

                        2 -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.healthAnalysis.healthAnalysisAll.top
                            )

                        }

                        3 -> {
                            binding.scrollView.smoothScrollTo(
                                0,
                                binding.tiaolifangan.tiaolifanganAll.top
                            )

                        }

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

                }
            }

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

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

        }
        )

        binding.scrollView.setOnScrollChangeListener(object : OnScrollChangeListener {
            override fun onScrollChange(
                v: NestedScrollView?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if (!isSelectTable) {
                    Log.e("mTag","移动的${scrollY}")
                    isScrollTable = true
                    if (scrollY >= binding.tiaolifangan.tiaolifanganAll.top) {
                        if (binding.xTablayout.selectedTabPosition != 3) {
                            binding.xTablayout.getTabAt(3)?.select()
                        }
                    } else if (scrollY >= binding.healthAnalysis.healthAnalysisAll.top) {
                        if (binding.xTablayout.selectedTabPosition != 2) {
                            binding.xTablayout.getTabAt(2)?.select()
                        }
                    } else if (scrollY >= binding.tongueIdentify.tongueIdentifyAll.top) {
                        if (binding.xTablayout.selectedTabPosition != 1) {
                            binding.xTablayout.getTabAt(1)?.select()
                        }
                    } else {
                        if (binding.xTablayout.selectedTabPosition != 0) {
                            binding.xTablayout.getTabAt(0)?.select()
                            binding.xTablayout.setScrollPosition(0, 0F, true)
                        }
                    }
                    isScrollTable = false
                }

            }
        })
    }

    fun initMyView(){
        bean = (activity as TongueDetailActivity).bean
        if (bean.status == 5) {
            binding.llReport.visibility = View.VISIBLE
            binding.clEmpty.visibility = View.GONE
            initTab()
            initReportView()
        } else {
            binding.llReport.visibility = View.GONE
            binding.clEmpty.visibility = View.VISIBLE
        }


    }

    private fun initReportView() {
        initUserInfo()
        initHealthState()
        initTongueIdentify()
        initHealthAnalysis()
        initTiaolifangan()
    }

    private fun initTiaolifangan() {
        binding.tiaolifangan.recyclerYWBJ.layoutManager = LinearLayoutManager(this.requireContext())
        var ywbjAdapter = DrugCareAdapter()
        binding.tiaolifangan.recyclerYWBJ.adapter = ywbjAdapter
        bean.tongueResultJson.treatPlanJson[0].drug_health_care[bean.tongueResultJson.treatPlanJson[0].drug_health_care.size - 1].isLast = true
        ywbjAdapter.setNewInstance(bean.tongueResultJson.treatPlanJson[0].drug_health_care as MutableList<DrugHealthCare>)

        binding.tiaolifangan.recyclerXWBJ.layoutManager = LinearLayoutManager(this.requireContext())
        var xwbjAdapter = XWAMAdapter()
        binding.tiaolifangan.recyclerXWBJ.adapter = xwbjAdapter
        xwbjAdapter.setNewInstance(bean.tongueResultJson.treatPlanJson[0].massage_health_care as MutableList<MassageHealthCare>)

        var textYSTY = ""
        bean.tongueResultJson.treatPlanJson[0].diet_rehabilitation_v2022.eatingHabits.forEachIndexed { index, eatingHabit ->
            if (index == bean.tongueResultJson.treatPlanJson[0].diet_rehabilitation_v2022.eatingHabits.size - 1) {
                textYSTY += "【${eatingHabit.title}】${eatingHabit.content}"
            } else {
                textYSTY += "【${eatingHabit.title}】${eatingHabit.content}\n"
            }
        }
        binding.tiaolifangan.tvYSTY.text = textYSTY

        binding.tiaolifangan.recyclerYSTZ.layoutManager = LinearLayoutManager(this.requireContext())
        var ystzAdapter = EatAdapter()
        binding.tiaolifangan.recyclerYSTZ.adapter = ystzAdapter
        ystzAdapter.setNewInstance(bean.tongueResultJson.treatPlanJson[0].diet_rehabilitation_v2022.dietaryRecuperate as MutableList<DietaryRecuperate>)

        var textYDBJ = ""
        bean.tongueResultJson.treatPlanJson[0].sports_health_care.forEachIndexed { index, sportsHealthCare ->
            if (index == bean.tongueResultJson.treatPlanJson[0].sports_health_care.size -1 ) {
                textYDBJ += sportsHealthCare.message
            } else {
                textYDBJ += sportsHealthCare.message + "\n"
            }
        }
        binding.tiaolifangan.tvYDBJ.text = textYDBJ

        var textQZTY = ""
        bean.tongueResultJson.treatPlanJson[0].recuperates.forEachIndexed { index, recuperate ->
            if (index == bean.tongueResultJson.treatPlanJson[0].recuperates.size -1 ) {
                textQZTY += recuperate.message
            } else {
                textQZTY += recuperate.message + "\n"
            }
        }
        binding.tiaolifangan.tvQZTY.text = textQZTY
    }

    private fun initHealthAnalysis() {
        var text = ""
        bean.tongueResultJson.treatPlanJson[0].main_performance.forEach {
            text += it.message + "\n"
        }
        binding.healthAnalysis.tvZhuYaoBiaoXian.text = text

        binding.healthAnalysis.ivBody.setImage(this.requireContext(),bean.tongueResultJson.treatPlanJson[0].high_risk_disease[0].img)

        val symptomList = bean.tongueResultJson.treatPlanJson[0].high_risk_disease[0].message.split(",")

        symptomList.forEach {
            var textView = layoutInflater.inflate(R.layout.view_question_body_text,null)
            textView.findViewById<TextView>(R.id.textView).text = it
            binding.healthAnalysis.llBodyQuestion.addView(
                textView
            )
        }

        var textFSYY = ""

        bean.tongueResultJson.treatPlanJson[0].occur_reason.forEach {
            textFSYY += it.message + "\n"
        }

        binding.healthAnalysis.tvFSYY.text = textFSYY

        var mIndex = 0
        bean.tongueResultJson.illProbability.illProbabilities.forEachIndexed { index, illProbabilities ->
            if (illProbabilities.name.equals(bean.solartermsName)) {
                mIndex = index
            }
        }


        var mData = bean.tongueResultJson.illProbability.illProbabilities[mIndex]

//        binding.healthAnalysis.tvJQFXTip.text = "提示：${bean.tongueResultJson.illProbability.explanation}"
        binding.healthAnalysis.tvJQFXTip.text = "提示：${mData.tip}\n说明：${bean.tongueResultJson.illProbability.explanation}"
        binding.healthAnalysis.tvNowJieqi.text = "当前节气：${mData.name}"
        binding.healthAnalysis.tvHBFX.text = "患病风险：${mData.level}"

        // 从数据中创建 Entry 列表和标签列表
        val entries = mutableListOf<Entry>()
        val labels = mutableListOf<String>()
        val data = bean.tongueResultJson.illProbability.illProbabilities // 替换为你的数据列表

        for ((index, item) in data.withIndex()) {
            entries.add(Entry(index.toFloat(), item.probability.toFloat()))
            labels.add(item.name)
        }

        // 创建数据集
        val dataSet = LineDataSet(entries, "概率")
        dataSet.color = Color.BLUE
        dataSet.color = this.getColor(R.color.col_25C)
        dataSet.valueTextColor = Color.BLACK
        dataSet.setDrawCircles(true) // 显示数据点
        dataSet.setDrawValues(false)  // 不显示数据值
        dataSet.mode = LineDataSet.Mode.CUBIC_BEZIER

        dataSet.setDrawCircles(false)
        // 创建 LineData 对象并设置数据集
        val lineData = LineData(dataSet)

        // 设置 X 轴值（标签）
        val xAxis = binding.healthAnalysis.mLineChart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.valueFormatter = IndexAxisValueFormatter(labels)
        xAxis.setDrawGridLines(false) // 不显示网格线
        xAxis.granularity = 1f // 设置X轴标签之间的最小间隔为1个单位
        xAxis.labelRotationAngle = -75f // 设置X轴标签的旋转角度为-90度，即竖着显示
        // 设置X轴标签数量
        xAxis.labelCount = 24


        // 设置左侧的 Y 轴
        val leftYAxis = binding.healthAnalysis.mLineChart.axisLeft
        leftYAxis.setDrawGridLines(false) // 不显示网格线

        // 隐藏右侧的 Y 轴
        binding.healthAnalysis.mLineChart.axisRight.isEnabled = false

        // 设置 LineChart 的其他属性
        binding.healthAnalysis.mLineChart.data = lineData
        binding.healthAnalysis.mLineChart.description.isEnabled = false // 不显示描述
        binding.healthAnalysis.mLineChart.legend.isEnabled = false // 不显示图例
        binding.healthAnalysis.mLineChart.setTouchEnabled(true) // 禁用触摸
        binding.healthAnalysis.mLineChart.setPinchZoom(true) // 禁用缩放

        val markerView = CustomMarkerView(this.requireContext(), R.layout.marker_view)
        binding.healthAnalysis.mLineChart.marker = markerView // 设置 MarkerView

        // 设置默认选中的数据点
        val highlight = Highlight(mIndex.toFloat(), 5f, 0) // 选择第 3 个数据点（X轴坐标为2，Y轴坐标为5）
        binding.healthAnalysis.mLineChart.highlightValue(highlight, false)


        // 更新图表
        binding.healthAnalysis.mLineChart.invalidate()


        val xLabels = arrayOf("心", "膀胱", "肾", "肺", "脾","肝")
        // 初始化数据
        val radarDatas = ArrayList<RadarEntry>()
        var showTip = false
//        "心", "膀胱", "肾", "肺", "脾","肝"
        xLabels.forEach { labels ->
            var location = bean.tongueResultJson.syndromesElement.locationList.filter { it.name.equals(labels) }
            if (location.size > 0) {
                radarDatas.add(RadarEntry(1f))
                showTip = true
            } else {
                radarDatas.add(RadarEntry(0f))
            }
        }

        if (showTip) {
            binding.healthAnalysis.tvChartTip.visibility = View.VISIBLE
            var mText = ""
            bean.tongueResultJson.syndromesElement.locationList.forEachIndexed { index, nature ->
                if (xLabels.filter { it.equals(nature.name) }.size > 0) {
                    if (index == bean.tongueResultJson.syndromesElement.locationList.size - 1) {
                        mText += nature.name
                    } else {
                        mText += nature.name + "、"
                    }
                }
            }
            if (mText.endsWith("、")) {
                // 字符串以逗号结尾，需要去掉
                mText = mText.substring(0, mText.length - 1);
            }
            binding.healthAnalysis.tvChartTip.text = "提示 : ${mText}欠佳"
        } else {
            binding.healthAnalysis.tvChartTip.visibility = View.GONE
        }
//        radarDatas.add(RadarEntry(0.2f)) // 心
//        radarDatas.add(RadarEntry(1f)) // 肝
//        radarDatas.add(RadarEntry(0.2f)) // 脾
//        radarDatas.add(RadarEntry(1f)) // 肺
//        radarDatas.add(RadarEntry(0.2f)) // 肾
//        radarDatas.add(RadarEntry(0.2f)) // 肾

        // 创建数据集
        val radarDataSet = RadarDataSet(radarDatas, "器官得分")
        radarDataSet.setDrawValues(false)
        radarDataSet.color = this.getColor(R.color.col_25C)
        radarDataSet.setDrawFilled(true) // 启用区域填充
        radarDataSet.fillColor = this.getColor(R.color.col_B0EDF2) // 设置区域填充颜色

        // 创建 RadarData
        val radarData = RadarData(radarDataSet)
        radarData.setValueTextSize(12f)
        radarData.setValueTextColor(Color.BLACK)

        // 配置 RadarChart
        binding.healthAnalysis.radarChart.data = radarData
        binding.healthAnalysis.radarChart.webLineWidth = 1.5f
        binding.healthAnalysis.radarChart.webColor = Color.GRAY
        binding.healthAnalysis.radarChart.webLineWidthInner = 1.5f
        binding.healthAnalysis.radarChart.webColorInner = Color.GRAY
        binding.healthAnalysis.radarChart.webAlpha = 100

        // 设置 X 轴标签

        binding.healthAnalysis.radarChart.xAxis.valueFormatter = object : IAxisValueFormatter{
            override fun getFormattedValue(value: Float, axis: AxisBase?): String {
                val index = value.toInt() % xLabels.size
                return xLabels[index]
            }

        }

        // 获取Y轴对象
        val yAxis = binding.healthAnalysis.radarChart.yAxis

        // 设置Y轴的最小值和最大值
        yAxis.axisMinimum = 0f
        yAxis.axisMaximum = 1f



        binding.healthAnalysis.radarChart.description.isEnabled = false
        binding.healthAnalysis.radarChart.legend.isEnabled = false
        binding.healthAnalysis.radarChart.yAxis.setDrawLabels(false)

        // 刷新图表
        binding.healthAnalysis.radarChart.invalidate()

    }


    private fun initTongueIdentify() {
        binding.tongueIdentify.ivTopImage.setImage(this.requireContext(),bean.imageUrl)
        binding.tongueIdentify.ivBottomImage.setImage(this.requireContext(),bean.backImageUrl)
        binding.tongueIdentify.tvSheSe.text = bean.tongueResultJson.colorOfTongueNames
        binding.tongueIdentify.tvTaiSe.text = bean.tongueResultJson.colorOfMossNames
        binding.tongueIdentify.tvSheXing.text = bean.tongueResultJson.shapeOfTongueNames
        binding.tongueIdentify.tvTaiZhi.text = bean.tongueResultJson.mossNames
        binding.tongueIdentify.tvJingYe.text = bean.tongueResultJson.bodyfluidNames
        binding.tongueIdentify.tvMaiLuo.text = bean.tongueResultJson.veinNames

        binding.tongueIdentify.ivTongueColor.setImage(this.requireContext(),bean.tongueResultJson.ossSplitImgUrl)
        binding.tongueIdentify.tvBSJG.text = bean.tongueResultJson.colorOfTongueNames

        val contentWithoutBrackets = bean.tongueResultJson.colorOfTongueDescribe.replace(Regex("\\【[^\\】]+\\】"), "")

        // 根据</br>截断
        val parts = contentWithoutBrackets.split("</br>")
        var textZYMS = ""
        var textBLYY = ""


        if (!parts.isEmpty() && parts.size >= 2) {
            textZYMS = parts[0]
            textBLYY = parts[1]
        }

        binding.tongueIdentify.tvZYMS.text = textZYMS
        binding.tongueIdentify.tvBLYY.text = textBLYY
    }

    private fun initHealthState() {
        binding.healthState.tvScore.text = "风险评分：${bean.tongueResultJson.illProbability.scope}分"
        binding.healthState.tvHealthState.text = bean.tongueResultJson.constitutionNames
        binding.healthState.tvHealthSuggest.text = bean.tongueResultJson.illProbability.tip
        binding.healthState.gaugeView.setValue(bean.tongueResultJson.illProbability.scope.toInt())
    }

    private fun initUserInfo() {
        binding.userInfo.tvUserName.text = bean.realName
        binding.userInfo.tvUserSex.text = if (bean.sex.equals("1")) "男" else "女"
        binding.userInfo.tvUserAge.text = bean.age + "岁"
        binding.userInfo.tvReportTime.text = bean.reportTime
    }

    override fun observer() {

    }

    // 自定义 MarkerView
    class CustomMarkerView(context: android.content.Context?, layoutResource: Int) : MarkerView(context, layoutResource) {
        override fun refreshContent(e: Entry?, highlight: Highlight?) {

            // 显示数据值
            val tvContent = findViewById<TextView>(R.id.tvContent)
            tvContent.text = "${e?.y}%"
            super.refreshContent(e, highlight)
        }

        override fun getOffset(): MPPointF {
            return MPPointF(-width.toFloat() / 2, -height.toFloat())
        }
    }

}