package com.zxhyis.toolss.ui.page.recentusage

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.Legend.LegendForm
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.XAxis.XAxisPosition
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.ironsource.z
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.databinding.FragmentScreenTimeBinding
import com.zxhyis.toolss.logic.AppBean
import com.zxhyis.toolss.logic.ReportInterface
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.ui.dialog.TimeSelectDialog.showTimeSelectDialog
import com.zxhyis.toolss.ui.page.recentusage.RecentAppAdapter.Companion.UI_SCREEN_TIME_MODE
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel
import java.text.SimpleDateFormat
import kotlin.random.Random
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit


/**
 */
class ScreenTimeFragment : Fragment(), ReportInterface {

    private lateinit var binding: FragmentScreenTimeBinding
    private var simpleDateFormat2 = SimpleDateFormat("(yyyy/MM/dd)")
    private lateinit var adapter: RecentAppAdapter
    private val dataList = arrayListOf<AppBean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_screen_time, container, false)
        binding = FragmentScreenTimeBinding.bind(root)
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setTextFont()
        binding.llDate.setOnClick(javaClass.simpleName) {
            requireContext().showTimeSelectDialog {
                when (it) {
                    AppViewModel.PAST_60_MINUS_QUERY -> {
                        recent60UI()
                    }

                    AppViewModel.TODAY_QUERY -> {
                        todayUI()
                    }

                    AppViewModel.YESTERDAY_QUERY -> {
                        yesterdayUI()
                    }

                    AppViewModel.SEVEN_DAYS_QUERY -> {
                        sevenDaysUI()
                    }
                }
            }
        }
        adapter = RecentAppAdapter(requireActivity(), UI_SCREEN_TIME_MODE)
        binding.rv.adapter = adapter
        adapter.setData(dataList)
        todayUI(false)
//        initChart()
        pageReport()
    }

    private fun initChart() {
        //整体配置
        binding.chart.setPinchZoom(false)
        binding.chart.setDrawGridBackground(false)
        binding.chart.description = Description().apply { text = "" }


        //x坐标
        val xAxisFormatter = AppScreenValueFormatter(binding.chart)
        val xAxis: XAxis = binding.chart.xAxis
        xAxis.position = XAxisPosition.BOTTOM
        xAxis.setDrawGridLines(false)
        xAxis.setGranularity(1f) // x最小间隔
        xAxis.setLabelCount(7) //几列x尺度
        xAxis.valueFormatter = xAxisFormatter


        //右边Y坐标
        val yFormatter = MyValueFormatter("m")
        val rightAxis: YAxis = binding.chart.axisRight
        rightAxis.setDrawGridLines(false)
        rightAxis.setLabelCount(8, false)
        rightAxis.valueFormatter = yFormatter
        rightAxis.spaceTop = 15f
        rightAxis.setAxisMinimum(0f)

        val l: Legend = binding.chart.legend
        l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
        l.form = LegendForm.SQUARE
        l.formSize = 9f
        l.setTextSize(11f)
        l.xEntrySpace = 4f


        val values = ArrayList<BarEntry>()
        repeat(20) {
            values.add(BarEntry(it.toFloat(), Random.nextInt(0, 13).toFloat()))
        }

        //数据集
        val set: BarDataSet = BarDataSet(values, "The year 2017")

//        binding.chart.data.notifyDataChanged()
//        binding.chart.notifyDataSetChanged()

        //数据集列表
        val dataSets = ArrayList<IBarDataSet>()
        dataSets.add(set)

        //添加数据
        val data = BarData(dataSets)
        data.setValueTextSize(10f)
        binding.chart.data = data
    }


    private fun setTextFont() {
        val fontMedium = "sans-serif-medium"
        val fontMediumTypeface = Typeface.create(fontMedium, Typeface.NORMAL)
        binding.tvDate.setTypeface(fontMediumTypeface)
    }

    @SuppressLint("SetTextI18n")
    fun todayUI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Today" + simpleDateFormat2.format(System.currentTimeMillis())
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(AppViewModel.TODAY_QUERY, 1)
        }
    }

    @SuppressLint("SetTextI18n")
    fun recent60UI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Recent 60 minus"
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(AppViewModel.PAST_60_MINUS_QUERY, 1)
        }
    }

    @SuppressLint("SetTextI18n")
    fun yesterdayUI(isReFresh: Boolean = true) {
        binding.tvDate.text =
            "Yesterday" + simpleDateFormat2.format(
                System.currentTimeMillis() - 24.hours.toLong(
                    DurationUnit.MILLISECONDS
                )
            )
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(AppViewModel.YESTERDAY_QUERY, 1)
        }
    }

    @SuppressLint("SetTextI18n")
    fun sevenDaysUI(isReFresh: Boolean = true) {
        binding.tvDate.text = "Last 7 days"
        if (isReFresh) {
            (requireActivity() as RecentAppActivity).changeTimeRefresh(AppViewModel.SEVEN_DAYS_QUERY, 1)
        }
    }

    fun setScreenData(dataList: ArrayList<AppBean>) {
        this.dataList.clear()
        this.dataList.addAll(dataList.filter { it.screenTime > 0 })
        if (isVisible) {
            adapter.setData(this.dataList)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun pageReport() {
        EventHelper.event("page_${javaClass.simpleName}")
    }

}