package net.huansi.app.hssummarizingboard.activity.main

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.animation.Animation
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import baseform.android.huansi.net.log.HsLog
import baseform.android.huansi.net.util.AndroidTableManager
import baseform.android.huansi.net.util.BasicVariableUtils
import baseform.android.huansi.net.util.RecyclerViewUtils
import baseform.android.huansi.net.util.ShareUtil
import baseform.android.huansi.net.util.charts.BarChartManager
import baseform.android.huansi.net.util.charts.PieChartManager
import baseform.android.huansi.net.util.charts.bean.BarValueBean
import baseform.android.huansi.net.util.charts.bean.PieValueBean
import baseform.android.huansi.net.util.charts.setting.*
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.Legend.LegendHorizontalAlignment
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.utils.Fill
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.huansi.app.hssummarizingboard.R
import net.huansi.app.hssummarizingboard.adapter.BrandAdapter
import net.huansi.app.hssummarizingboard.base.SutureClothBaseActivity
import net.huansi.app.hssummarizingboard.databinding.ActivityMainBinding
import net.huansi.app.hssummarizingboard.entity.BrandBean
import net.huansi.app.hssummarizingboard.entity.BrandInfoBean
import net.huansi.app.hssummarizingboard.entity.PieChartBean
import net.huansi.app.hssummarizingboard.entity.ProDetailsBean
import net.huansi.app.hssummarizingboard.utils.Constant
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : SutureClothBaseActivity<ActivityMainBinding, MainPresenter>() {
    private var pageCountdownSeconds: Long = 5//页面刷新时间
    private lateinit var mBrandPieChart: PieChartManager
    private lateinit var mProductionBarChart: BarChartManager

    //品牌列表
    private lateinit var mBrandAdapter: BrandAdapter
    private val mBrandList = mutableListOf<BrandBean>()

    //优秀区当前页码
    private var excellenceAreaIndex: Int = -1

    //潜能区当前页码
    private var potentialAreaIndex: Int = -1

    //产前事件详情区当前页码
    private var proDetailsIndex: Int = -1

    //品牌当前页码
    private var brandIndex: Int = -1

    //品牌当前选中页码
    private var brandPresentPos = -1

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun init() {
        super.init()
        pageCountdownSeconds = ShareUtil.getLong(Constant.SP_DATA_REFRESH_TIME, 5)
        mBrandAdapter = BrandAdapter(mBrandList, this)
        RecyclerViewUtils.initDefaultList(
            mBinding.includeAreaRight.recyBrand,
            this,
            mBrandAdapter
        )
        val layoutManager = mBinding.includeAreaRight.recyBrand.layoutManager as LinearLayoutManager
        layoutManager.orientation = RecyclerView.HORIZONTAL

        mBrandPieChart = PieChartManager(mBinding.includeAreaRight.pcBrandPieChart)
        mProductionBarChart = BarChartManager(mBinding.includeAreaBot.bcProductionBarChart)

        animationStart()

        lifecycleScope.launch(Dispatchers.Main) {
            baseForm.startDateTimeRefreshTimer {
                lifecycleScope.launch(Dispatchers.Main) {
                    val remainingSeconds =
                        pageCountdownSeconds - (it.toInt()) % (pageCountdownSeconds + 1)

                    if (remainingSeconds <= 0) {
                        refreshData()
                    }
                    refreshTimeRealTime()
                }
            }
            refreshData()
        }
    }

    //刷新数据
    private suspend fun refreshData() {
        excellenceAreaIndex++
        potentialAreaIndex++
        proDetailsIndex++
        brandIndex++

        //中心统计
        baseForm.requestStatisticsData()?.let {
            mBinding.includeAreaMiddle.tvTotalTask.text = it.total_task
            mBinding.includeAreaMiddle.tvCompleted.text = it.finished
            mBinding.includeAreaMiddle.tvIncomplete.text = it.unfinished
            mBinding.includeAreaMiddle.tvFinishOnTime.text = it.on_time_finished_hasty
            mBinding.includeAreaMiddle.tvProgress.text = it.on_time_unfinished_hasty
            mBinding.includeAreaMiddle.tvTimeoutFinish.text = it.timeout_finished_hasty
            mBinding.includeAreaMiddle.tvTimeoutNoFinish.text = it.out_time_unfinished_hasty
        }

        //优秀区
        val excellenceArea = baseForm.requestAreaData("excellent")
        excellenceArea?.let {
            val jsonArray = if (excellenceAreaIndex < it.pageCount) {
                it.contentList[excellenceAreaIndex]
            } else {
                excellenceAreaIndex = 0
                it.contentList[excellenceAreaIndex]
            }
            AndroidTableManager.refreshTable(
                mBinding.includeAreaLeft.tlExcellenceArea,
                this,
                jsonArray,
                true
            )
        }

        //潜能区
        val potentialArea = baseForm.requestAreaData("potential")
        potentialArea?.let {
            val jsonArray = if (potentialAreaIndex < it.pageCount) {
                it.contentList[potentialAreaIndex]
            } else {
                potentialAreaIndex = 0
                it.contentList[potentialAreaIndex]
            }
            AndroidTableManager.refreshTable(
                mBinding.includeAreaLeft.tlPotentialArea,
                this,
                jsonArray,
                true
            )
        }

        //设置饼图
        mBrandList.clear()
        val brandList = baseForm.requestBrandList()
        mBrandList.addAll(brandList)
        if (mBrandList.isNotEmpty()) {
            if (brandIndex >= mBrandList.size) brandIndex = 0
            mBrandList[brandIndex].isCheck = true
            mBrandList[brandIndex].infoList?.let {
                showBrandPieChart(it)
            }

            //设置背景色
            if (brandPresentPos >= 0) {
                mBrandList[brandPresentPos].isCheck = false
                mBrandAdapter.notifyItemChanged(brandPresentPos)
            }
            brandPresentPos = brandIndex
            mBrandList[brandPresentPos].isCheck = true
            mBrandAdapter.notifyDataSetChanged()
        }

        //设置柱状图
        val proDetailsList = baseForm.requestProDetails()
        val summaryDetails = baseForm.getSummaryDetails(proDetailsList)
        summaryDetails?.let {
            val jsonArray = if (proDetailsIndex < it.pageCount) {
                it.contentList[proDetailsIndex]
            } else {
                proDetailsIndex = 0
                it.contentList[proDetailsIndex]
            }
            AndroidTableManager.refreshTable(
                mBinding.includeAreaRight.tlSummaryDetails,
                this,
                jsonArray,
                true
            )
        }
        showData1(proDetailsList)
    }

    /**
     * 显示饼状图
     */
    private fun showBrandPieChart(list: List<BrandInfoBean>) {
        if (list.isEmpty()) {
            mBrandPieChart.chart.clear()
            return
        }

        //饼图内圆设置 --- 此项目不显示
        val holeSetting = PieInnerHoleSetting().apply { show = false }
        mBrandPieChart.setInnerHole(holeSetting)

        //饼图的每一个扇形
        val valueBeanList = list
            .mapIndexed { index, dataBean ->
                return@mapIndexed PieValueBean().apply {
                    value = dataBean.value.toFloatOrNull() ?: 0f
                    showValue = dataBean.value
                    color = when (index) {
                        0 -> {
                            resources.getColor(R.color.F3E93EC)
                        }
                        1 -> {
                            resources.getColor(R.color.red1)
                        }
                        2 -> {
                            resources.getColor(R.color.F7B00FF)
                        }
                        3 -> {
                            resources.getColor(R.color.F1DF2F7)
                        }
                        else -> {
                            resources.getColor(R.color.F3E93EC)
                        }
                    }
                }
            }.toList()

        //文字的大小和颜色
        val textFontSetting = TextFontSetting().apply {
            textSize = 10f
            textColor = resources.getColor(R.color.white)
        }
        //折线
        val pieMarkSetting = PieMarkSetting().apply {
            length1 = 0.5f
            color = resources.getColor(R.color.white)
        }

        val totalValue = list.sumOf { it.value.toDoubleOrNull() ?: 0.0 }.toFloat()

        val barData = mBrandPieChart.getPieData(valueBeanList, textFontSetting, pieMarkSetting,
            f = IValueFormatter { value, entry, _, _ ->
                try {
                    return@IValueFormatter list[entry.data as Int % list.size].name +
                            "(${value}," +
                            "${BasicVariableUtils.saveDecimal(value / totalValue * 100.0, 1)}%)"
                } catch (e: Exception) {
                    return@IValueFormatter ""
                }
            })
        mBrandPieChart.setLegend(mutableListOf(), LegendSetting().apply { isShow = false })
        mBrandPieChart.show(barData)
    }

    //显示柱状图
    private fun showData1(list: List<ProDetailsBean>) {
        if (list.isEmpty()) {
            mProductionBarChart.chart.clear()
            return
        }

        //字体颜色和大小
        val defaultTextColor = resources.getColor(R.color.white)
        val defaultTextSize = 10f
        //图例
        val legendList = getChartLegend()
        //图例位置
        val legendSetting = LegendSetting().apply {
            isShow = true
            textSize = defaultTextSize
            textColor = defaultTextColor
            vertical = Legend.LegendVerticalAlignment.TOP
            horizontal = LegendHorizontalAlignment.RIGHT
        }

        //x轴信息
        val xList = list.map { it.job_name }.toList()
        val xSetting = XSetting().apply {
            isShow = true
            textSize = 8f
            textColor = defaultTextColor
            rotationAngle = -20f
        }
        //y轴配置
        val ySetting = YSetting().apply {
            isShow = true
            isGridShow = true
            textSize = defaultTextSize
            textColor = defaultTextColor
        }

        //设置x轴和Y轴显示
        mProductionBarChart.setX(xList, xSetting)
        mProductionBarChart.setY(true, ySetting, formatter = DefaultAxisValueFormatter(0))
        //隐藏右侧Y轴
        mProductionBarChart.setY(false, YSetting(), formatter = DefaultAxisValueFormatter(0))
        //设置图例显示
        mProductionBarChart.setLegend(legendList, legendSetting)

        val barValueList = getBarValue(list)
        val textFontSetting = TextFontSetting().apply {
            textSize = defaultTextSize
            textColor = defaultTextColor
        }
        val barData = mProductionBarChart.getSideBarData(barValueList, textFontSetting)
        barData.barWidth = 0.2f
        mProductionBarChart.show(barData)
    }

    //生成图例
    private fun getChartLegend(): List<ChartLegendBean> {
        val legendList: MutableList<ChartLegendBean> = mutableListOf()
        legendList.add(ChartLegendBean().apply {
            name = "总任务"
            color = resources.getColor(R.color.F027DB4)
        })
        legendList.add(ChartLegendBean().apply {
            name = "未完成"
            color = resources.getColor(R.color.Fff175e)
        })
        legendList.add(ChartLegendBean().apply {
            name = "按时完成"
            color = resources.getColor(R.color.F70B602)
        })
        legendList.add(ChartLegendBean().apply {
            name = "超时完成"
            color = resources.getColor(R.color.FF59A23)
        })
        return legendList.toList()
    }

    //生成柱状图
    private fun getBarValue(list: List<ProDetailsBean>): List<BarValueBean> {
        val barValueList: MutableList<BarValueBean> = mutableListOf()
        barValueList.add(BarValueBean().apply {
            list.mapIndexed { _, dataBean ->
                return@mapIndexed BarValueBean.BarValueDataBean().apply {
                    value = dataBean.total_task.toFloatOrNull() ?: 0f
                    showValue = dataBean.total_task
                    color = Fill(resources.getColor(R.color.F027DB4))
                }
            }.let { dataList.addAll(it) }
        })
        barValueList.add(BarValueBean().apply {
            list.mapIndexed { _, dataBean ->
                return@mapIndexed BarValueBean.BarValueDataBean().apply {
                    value = dataBean.unfinished.toFloatOrNull() ?: 0f
                    color = Fill(resources.getColor(R.color.Fff175e))
                }
            }.let { dataList.addAll(it) }
        })
        barValueList.add(BarValueBean().apply {
            list.mapIndexed { _, dataBean ->
                return@mapIndexed BarValueBean.BarValueDataBean().apply {
                    value = dataBean.on_time_finished.toFloatOrNull() ?: 0f
                    color = Fill(resources.getColor(R.color.F70B602))
                }
            }.let { dataList.addAll(it) }
        })
        barValueList.add(BarValueBean().apply {
            list.mapIndexed { _, dataBean ->
                return@mapIndexed BarValueBean.BarValueDataBean().apply {
                    value = dataBean.timeout_finished.toFloatOrNull() ?: 0f
                    color = Fill(resources.getColor(R.color.FF59A23))
                }
            }.let { dataList.addAll(it) }
        })
        return barValueList.toList()
    }

    //实时刷新时间
    @SuppressLint("SimpleDateFormat")
    private fun refreshTimeRealTime() {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")
        val date = Date()
        val showDate = dateFormat.format(date)
        val weekList = listOf("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
        val calendar = Calendar.getInstance()
        calendar.time = date
        var weekIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1
        if (weekIndex < 0) weekIndex = 0
        mBinding.tvCurrentDate.text = "${showDate} ${weekList[weekIndex % weekList.size]}"
    }

    /**
     * 动画
     */
    private fun animationStart() {
        val animator =
            ObjectAnimator.ofFloat(mBinding.includeAreaMiddle.ivCloud, "translationY", 0F, 30F, 0F)
        animator.repeatMode = ValueAnimator.REVERSE
        animator.repeatCount = Animation.INFINITE
        animator.duration = 2000
        animator.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        baseForm.stopDateTimeRefreshTimer()
    }

    companion object {
        fun toThis(from: Activity) {
            val intent = Intent(from, MainActivity::class.java)
            from.startActivity(intent)
        }
    }
}