package com.abbidot.tracker.ui.fragment.data

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.HomeDataBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentActivityV2Binding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.data.MoreActivityActivity
import com.abbidot.tracker.ui.activity.data.MoreSleepActivity
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.DataViewModel
import com.qmuiteam.qmui.widget.pullRefreshLayout.QMUIPullRefreshLayout


/**
 * 首页Activity
 * create an instance of this fragment.
 */
class ActivityV2Fragment :
    BaseFragment<FragmentActivityV2Binding>(FragmentActivityV2Binding::inflate) {

    private lateinit var mDataViewModel: DataViewModel

    //当前这个页面显示的宠物下标
    private var mCurrentShowPetPos = -1

    private var mToday = "2024-06-28"

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = ActivityV2Fragment().apply {
            mContext = context
        }
    }

    override fun initData() {

        mToday = Utils.getCurrentTime(Utils.DATE_FORMAT_PATTERN_CN)
        mViewBinding.apply {

            getHomeV2Activity()?.edgeToEdgeAdapterBars(
                svHomeActivityScroll, WindowInsetsCompat.Type.statusBars()
            )

            ilSportDistanceLayout.apply {
                ivSportDataType.setImageResource(R.drawable.icon_active_time)
                tvSportDataTitle.text = getString(R.string.txt_time)
                tvSportDataUnit.text = getString(R.string.txt_min)
            }

            ilSportActiveLayout.let {
                it.root.background =
                    ContextCompat.getDrawable(mContext!!, R.drawable.shape8_gray_yellow_bg)
                val tColor = ContextCompat.getColor(mContext!!, R.color.data_black_color)
                it.ivSportTimeType.setImageResource(R.drawable.icon_active_time)
                it.tvSportTimeTitle.text = getText(R.string.data_active_other_time)
                it.tvSportTimeTitle.setTextColor(tColor)
                it.tvSportTimeContent.setTextColor(tColor)
            }

            //下拉刷新
            homeActivityV2PullRefresh.setOnPullListener(object :
                QMUIPullRefreshLayout.OnPullListener {
                override fun onMoveTarget(offset: Int) {
                }

                override fun onMoveRefreshView(offset: Int) {
                }

                override fun onRefresh() {
                    getHomeV2Activity()?.getPet()?.apply {
                        mDataViewModel.getHomeDeviceData(deviceId, mToday, petId)
                    }
                }
            })

            setOnClickListenerViews(
                ilHomeActivityTopPet.ivTopPetBtnSmall,
                btnHomeMoreActivity,
                btnHomeMoreSleep,
                ilHomeActivityTopPet.homeDataPetNameSmall,
                ilHomeActivityTopPet.homeDataPetHeadSmall.root
            )

            if (AppUtils.isDebug()) {
                ilHomeActivityTopPet.homeDataPetHeadSmall.root.setOnLongClickListener {
                    getHomeV2Activity()?.goToDebugActivity()
                    true
                }
            }

//            val activityList = mutableListOf(28, 54, 69, 110, 88, 39, 78, 12, 68, 98, 46, 93)
//            homeActiveTimeBarView.setData(activityList)
//            homeActiveSleepView.setData(3f, 5f)
        }

        //切换到账户AccountV2Fragment 页面，会导致ViewModel生命周期销毁，需要重新创建
        mDataViewModel = ViewModelProvider(this)[DataViewModel::class.java]

        initHomeData()
    }

    private fun getHomeV2Activity(): HomeV2Activity? {
        return if (null == activity) {
            LogUtil.e("ActivityV2Fragment,getHomeV2Activity,null == activity")
            null
        } else {
            activity as HomeV2Activity
        }
    }


    private fun initHomeData() {
        val goal = MMKVUtil.getInt(MMKVKey.ActivityGoal)
        mViewBinding.apply {
            homeActiveTimeProgress.progress = 0
            tvHomeActivityV2GoalPercent.text =
                String.format(getString(R.string.txt_goal_percent), "0")
            tvHomeActivityV2Goal.text =
                String.format(getString(R.string.txt_min_unit_lower), "0/$goal")
            ilSportDistanceLayout.let {
                it.tvSportDataContent.text = "0"
//                it.tvSportDataUnit.text = Util.getMetricUnits(mContext!!, ConstantInt.Type4)
            }
            ilSportCaloriesLayout.let {
                it.ivSportDataType.setImageResource(R.drawable.icon_calories)
                it.tvSportDataTitle.text = getString(R.string.data_active_calories)
                it.tvSportDataContent.text = "0"
                it.tvSportDataUnit.text = getString(R.string.txt_calorie_unit)
            }
            ilSportActiveLayout.tvSportTimeContent.text = "00:00:00"
            ilSportSleepLayout.tvSportTimeContent.text = "00:00:00"
            homeActiveTimeBarView.setData(mutableListOf())
            homeActiveSleepView.setData(0f, 0f)
        }
    }

    override fun onResume() {
        super.onResume()
        getHomeV2Activity()?.let {
            if (mCurrentShowPetPos == it.mSelectPetPosition) {
                it.getPet()?.apply {
                    mDataViewModel.getHomeDeviceData(deviceId, mToday, petId)
                }
            } else {
                //其他页面是否选择了宠物
                showPetNameAndHead(it.mSelectPetPosition)
            }
            checkNotifyLocationState()
        }
    }

    fun checkNotifyLocationState() {
        getHomeV2Activity()?.apply {
            checkNotifyRefreshLocation(mViewBinding.ilHomeActivityTopPet.homeDataPetNameSmall)
        }
    }

    override fun liveDataObserve() {
        mDataViewModel.mHomeDataLiveData.observe(viewLifecycleOwner) {
            initHomeData()
            mViewBinding.let { v ->
                if (v.homeActivityV2PullRefresh.isRefreshing) {
                    v.homeActivityV2PullRefresh.finishRefresh()
                }
            }
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        setHomeData(this)
                    }
                }
            })
        }
    }

    private fun setHomeData(homeDataBean: HomeDataBean) {
        mViewBinding.apply {
            var goal = ConstantInt.DefaultSportGoal
            var activeTime = 0

            val updateTime = if (homeDataBean.updateTime == 0L) {
                Utils.formatTime(System.currentTimeMillis(), Utils.DATE_FORMAT_PATTERN_EN15)
            } else {
                Utils.formatTime(homeDataBean.updateTime * 1000, Utils.DATE_FORMAT_PATTERN_EN15)
            }
            tvHomeActivityV2UpdateTime.text =
                String.format(getString(R.string.txt_update_time), updateTime)

            homeDataBean.activeTime?.let {

                ViewUtil.instance.viewNumberValueAnimator(
                    ilSportDistanceLayout.tvSportDataContent, 0, it.activeTime / 60
                )
//                ViewUtil.instance.viewNumberValueAnimator(
//                    ilSportDistanceLayout.tvSportDataContent,
//                    0,
//                    Util.metricConvertUnits(it.distance.toFloat(), ConstantInt.Type4, 2)
//                )
                ViewUtil.instance.viewNumberValueAnimator(
                    ilSportCaloriesLayout.tvSportDataContent, 0, it.calories
                )
                if (it.goalTime >= ConstantInt.MinSportGoal) goal = it.goalTime

                activeTime = it.activeTime
                timeConversionValueAnimator(ilSportActiveLayout.tvSportTimeContent, activeTime)
                val activeMin = activeTime / 60
                tvHomeActivityV2Goal.text =
                    String.format(getString(R.string.txt_min_unit_lower), "$activeMin/$goal")
                var goalPercent = activeMin / goal.toFloat()
                goalPercent = Utils.formatDecimal(goalPercent, 2).toFloat()
                goalPercent *= 100
                ViewUtil.instance.viewNumberValueAnimator(
                    tvHomeActivityV2GoalPercent,
                    0,
                    goalPercent.toInt(),
                    getString(R.string.txt_goal_percent)
                )
                ViewUtil.instance.viewNumberValueAnimator(
                    homeActiveTimeProgress, 0, goalPercent.toInt()
                )

                if (!TextUtils.isEmpty(it.activeValue)) {
                    val activeTimeList = mutableListOf<Int>()
                    val activeList = it.activeValue.split(",")
                    for (i in activeList.indices step 2) {
                        val time = activeList[i].toInt() + activeList[i + 1].toInt()
                        activeTimeList.add(time / 60)
                    }
                    homeActiveTimeBarView.setData(activeTimeList)
                }
            }

            homeDataBean.sleepTime?.let {
                timeConversionValueAnimator(
                    ilSportSleepLayout.tvSportTimeContent, it.sleepTime
                )
                homeActiveSleepView.setData(activeTime.toFloat(), it.sleepTime.toFloat())
            }
        }
    }

    /**
     * 时间动画显示
     */
    private fun timeConversionValueAnimator(textView: TextView, time: Int) {
        if (time == 0) return
        ViewUtil.instance.setValueAnimator(0, time, 1500) {
            val value = it.animatedValue as Int
            textView.text = Utils.timeConversion(value)
        }
    }

    override fun onDetach() {
        super.onDetach()
        mCurrentShowPetPos = -1
    }

    /**
     * 设置需要更新的标识
     */
    fun setNeedUpdateTag() {
        mCurrentShowPetPos = -1
    }

    /**
     * 显示选择的宠物
     */
    fun showPetNameAndHead(position: Int) {
        getHomeV2Activity()?.let {
            if (it.mPetList.size == 0) {
                return
            }
            mCurrentShowPetPos = position

            ViewUtil.instance.selectPetDialogShow(
                mContext!!,
                it.mPetList,
                position,
                mViewBinding.ilHomeActivityTopPet.homeDataPetNameSmall,
                mViewBinding.ilHomeActivityTopPet.homeDataPetHeadSmall.appHeadImage
            )

            it.getPet()?.apply {
                mDataViewModel.getHomeDeviceData(deviceId, mToday, petId)
            }
        }
    }

    private fun goActivityNeedPet(cls: Class<*>) {
        getHomeV2Activity()?.getPet()?.apply {
            Intent(mContext, cls).let {
                it.putExtra(ConstantString.Pet, this)
                startActivity(it)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilHomeActivityTopPet.ivTopPetBtnSmall -> getHomeV2Activity()?.getPet()?.apply {
                    ViewUtil.instance.viewAlphaAndRotationObjectAnimator(v)
                    mDataViewModel.getHomeDeviceData(deviceId, mToday, petId)
                }

                btnHomeMoreActivity -> goActivityNeedPet(MoreActivityActivity::class.java)

                btnHomeMoreSleep -> goActivityNeedPet(MoreSleepActivity::class.java)

                ilHomeActivityTopPet.homeDataPetNameSmall, ilHomeActivityTopPet.homeDataPetHeadSmall.root -> {
                    getHomeV2Activity()?.let {
                        if (!it.isNotifyRefreshLocation) it.selectPetDialog()
                    }
                }
            }

        }
    }
}