package com.abbidot.tracker.ui.activity.data

import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.SleepTimeBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityMoreSleepBinding
import com.abbidot.tracker.dialog.ShowCalenderDialog
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.DataDetailViewModel
import com.haibin.calendarview.Calendar

class MoreSleepActivity :
    BaseActivity<ActivityMoreSleepBinding>(ActivityMoreSleepBinding::inflate) {

    private val mDataDetailViewModel: DataDetailViewModel by viewModels()

    private var mCalenderDialog: ShowCalenderDialog? = null

    private var mPetBean: PetBean? = null

    private var mToday = ""

    override fun getTopBar() = mViewBinding.moreSleepTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setStatusBarDark()
        setTopBarTitle(R.string.txt_resting)

        intent.extras?.apply {
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        }

        mViewBinding.apply {
            root.background = ContextCompat.getDrawable(mContext, R.drawable.icon_more_sleep_bg)
            mTopBar!!.titleView?.setTextColor(ContextCompat.getColor(mContext, R.color.white))
            setLeftBackImage(R.drawable.icon_black_back_svg)
//            mRightImageButton = addRightImageButton(R.drawable.selector_share_icon_pressed2)

            mPetBean?.let {
                ViewUtil.instance.setPetTypeHead(
                    ilMoreSleepPetHead.appHeadImage, it.imgurl, it.petType
                )
                tvMoreSleepPetName.text = it.petName
            }
            tvSleepSelectCalendarShow.text =
                Utils.formatTime(System.currentTimeMillis(), Utils.DATE_FORMAT_PATTERN_EN4)

            setOnClickListenerViews(tvSleepSelectCalendarShow)

            sleepDataHorizontalCalenderView.setOnDaySelectedListener { hasChanged, year, month, day, week, items ->
                val curDate = "$year-${Utils.fill2Digits(month)}-${Utils.fill2Digits(day)}"
                val curTimestamp = Utils.stringToTimestamp(curDate, Utils.DATE_FORMAT_PATTERN_CN)
                val enDate = Utils.stringToDate(
                    curDate, Utils.DATE_FORMAT_PATTERN_CN, Utils.DATE_FORMAT_PATTERN_EN4
                )
//                mCalenderDialog?.setSelectDate(curTimestamp)
                tvSleepSelectCalendarShow.text = enDate
                getSleepTimeByDay(curDate)
            }

            sleepDataHorizontalCalenderView.setTodaySelectionBgTextColor(
                R.drawable.shape36_drak_green_color_bg, R.color.select_color2
            )
        }

        initSleepData()

        mToday = Utils.getCurrentTime(Utils.DATE_FORMAT_PATTERN_CN)
        getSleepTimeByDay(mToday)
    }

    override fun liveDataObserve() {
        mDataDetailViewModel.mSleepDetailLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        setSleepData(this)
                    }
                }
            })
        }
    }

    /**
     * 默认的数据
     */
    private fun initSleepData() {
        mViewBinding.apply {
            tvMoreSleepTimeSum.text = "0h 0m"
            tvTotalSleepTimeHourTitle.visibility = View.INVISIBLE
            tvTotalSleepTimeHour.visibility = View.INVISIBLE
            tvTotalSleepTimeMin.text = "0"

            moreSleepRingView.setData(0f, 1f)
            last7daySleepChartView.setData(mutableListOf())
            last30daySleepLineChartView.setData(mutableListOf())
        }
    }

    private fun getSleepTimeByDay(dayTime: String) {
        initSleepData()
        mPetBean?.apply {
            mDataDetailViewModel.getSleepTimeByDay(this@MoreSleepActivity, deviceId, dayTime, petId)
        }
    }

    private fun setSleepData(sleepTimeBean: SleepTimeBean) {
        mViewBinding.apply {
            sleepTimeBean.let {

                ViewUtil.instance.setValueAnimator(0, it.sleepTime, 1500) { v ->
                    val value = v.animatedValue as Int
                    val h = value / 3600
                    val m = (value % 3600) / 60
                    val str = "${h}h ${m}m"
                    tvMoreSleepTimeSum.text = str
                }

                val h = it.avgSleepTime / 3600
                val m = (it.avgSleepTime % 3600) / 60
                moreSleepRingView.setData(it.activeTime / 60f, it.sleepTime / 60f)
                if (h == 0) {
                    tvTotalSleepTimeHourTitle.visibility = View.INVISIBLE
                    tvTotalSleepTimeHour.visibility = View.INVISIBLE
                } else {
                    tvTotalSleepTimeHourTitle.visibility = View.VISIBLE
                    tvTotalSleepTimeHour.visibility = View.VISIBLE
                    ViewUtil.instance.viewNumberValueAnimator(tvTotalSleepTimeHour, 0, h)
                }
                ViewUtil.instance.viewNumberValueAnimator(tvTotalSleepTimeMin, 0, m)

                it.sevenDatas?.let { s ->
                    if (s.size > 0) {
                        val yAxis = mutableListOf<String>()
                        val data = mutableListOf<Int>()
                        for (a in s) {
                            val week = Utils.stringToDate(
                                a.dayTime, Utils.DATE_FORMAT_PATTERN_CN, Utils.WEEK_FORMAT_PATTERN
                            )
                            if (a.dayTime == mToday) yAxis.add(getString(R.string.txt_today))
                            else yAxis.add(week)
                            data.add(a.sleepTime / 60)
                        }
                        last7daySleepChartView.setData(data, yAxis, true)
                    }
                }

                it.thirtyDatas?.let { t ->
                    if (t.size > 0) {
                        val subList = if (t.size > 30) t.subList(0, 30) else t
                        val xAxis = mutableListOf<String>()
                        val data = mutableListOf<Int>()
                        var step = 0
                        var stepValue = 0
                        for (i in 0 until subList.size) {
                            val a = subList[i]
                            if (i == stepValue) {
                                val date = Utils.stringToDate(
                                    a.dayTime,
                                    Utils.DATE_FORMAT_PATTERN_CN,
                                    Utils.DATE_FORMAT_PATTERN_EN5
                                )
                                if (a.dayTime == mToday) xAxis.add(getString(R.string.txt_today))
                                else xAxis.add(date)
                                step++
                                stepValue = 6 * step - 1
                            }
                            val min = a.sleepTime / 60
                            data.add(min)
                        }
                        //反向输出
                        xAxis.reverse()
                        data.reverse()
                        last30daySleepLineChartView.setData(data, xAxis)
                    }
                }
            }
        }
    }

    private fun showCalenderDialog() {
        val cTimestamp = Utils.stringToTimestamp(
            mViewBinding.tvSleepSelectCalendarShow.text.toString(), Utils.DATE_FORMAT_PATTERN_EN4
        )
        val calenderDialog =
            ShowCalenderDialog(mContext, object : BaseDialog.OnDialogSelectListener {
                override fun onSelectClick(dialog: BaseDialog<*>, any: Any) {
                    if (any is Calendar) {
                        mViewBinding.sleepDataHorizontalCalenderView.setSelectedDate(
                            any.year, any.month, any.day
                        )
                    }
                }
            }, calenderShowTimestamp = cTimestamp, minLastDayRange = 29)
        calenderDialog.show()
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                tvSleepSelectCalendarShow -> showCalenderDialog()
            }
        }
    }
}