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

import android.content.Context
import android.view.Gravity
import android.view.View
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
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.BaseDialog
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentRouteV2Binding
import com.abbidot.tracker.dialog.ShowCalenderAndTimeDialog
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.common.map.HistoryDataMapCommon
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.DataDetailViewModel
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.widget.TypefaceTextView
import com.abbidot.tracker.widget.VerticalTopToBottomSeekBar
import kotlinx.coroutines.launch


/**
 * 首页轨迹
 * create an instance of this fragment.
 */
class RouteV2Fragment : BaseFragment<FragmentRouteV2Binding>(FragmentRouteV2Binding::inflate) {

    private val mDataDetailViewModel: DataDetailViewModel by viewModels()
    private val mGeoCoderViewModel: GeoCoderViewModel by viewModels()

    private lateinit var mFragment: Fragment

    private var mFromCalenderDialog: ShowCalenderAndTimeDialog? = null
    private var mToCalenderDialog: ShowCalenderAndTimeDialog? = null

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

    //最多只能选择多少天的历史记录
    private val mOnlySelectDay = 15L

    //当前的时间戳
    private var mCurrentTimestamp = 0L
    private var mFromTimestamp = 0L
    private var mToTimestamp = 0L

    //方便保存地理反编译信息
    private var mHistoryDataList = mutableListOf<HistoryDataBean>()
    private val mHistoryDataMapCommon = HistoryDataMapCommon()

    //是否选过自定义日期，没有则再次回到这个页面，刷新取24小时的记录
    private var isSelectCustomDate = false

    //    private var isFirst = true
    private var mProgress = -1

    //充值续费或升级返回类型
    private var mRechargeBackType = ConstantInt.SpecialType

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

    override fun initData() {
        mViewBinding.apply {
            getHomeV2Activity()?.edgeToEdgeAdapterBars(
                root, WindowInsetsCompat.Type.statusBars()
            )
            mFragment = mHistoryDataMapCommon.getMapFragment(
                mContext!!, miHomeRouteAddressView, mGeoCoderViewModel, vsbMapRouteLine
            ) {
                mapLoadOk()
            }

            ilHomeRoutePetHead.ivTopPetBtnSmall.visibility = View.GONE

            setOnClickListenerViews(
                llHomeRouteCalendarFrom,
                llHomeRouteCalendarTo,
//                ilHomeRoutePetHead.ivTopPetBtnSmall,
                ilHomeRoutePetHead.homeDataPetHeadSmall.root,
                ilHomeRoutePetHead.homeDataPetNameSmall,
                ivHomeRouteMapTypeBtn
            )

            val type = MMKVUtil.getInt(MMKVKey.LineSelectPosition, ConstantInt.Line)
            if (type == ConstantInt.Line) {
                mViewBinding.rbHistoryRouteMapLine.isChecked = true
            } else {
                mViewBinding.rbHistoryRouteMapNumber.isChecked = true
            }

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

        //解决报错java.lang.IllegalArgumentException
        //No view found for id 0x7f090254 (com.abbidot.tracker:id/fc_home_route_fragment) for fragment HomeMapGoogleMapFragment
        //https://www.jianshu.com/p/9235092f407a
        childFragmentManager.commit {
            add(R.id.fc_home_route_fragment, mFragment)
        }
//        (mActivity as FragmentActivity).supportFragmentManager.commit {
//            add(R.id.fc_home_route_fragment, mFragment)
//        }

        initEven()
        initState()
    }

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

    /**
     * 一开始获取24小时内的数据
     */
    private fun get24HourTime() {
        mCurrentTimestamp = System.currentTimeMillis()
        mViewBinding.apply {
            mFromTimestamp = Utils.getBeforeHowTimestamp(mCurrentTimestamp, 1)
            mToTimestamp = mCurrentTimestamp
            tvHomeRouteCalendarTo.text =
                Utils.formatTime(mToTimestamp, Utils.DATE_FORMAT_PATTERN_EN1)
            tvHomeRouteCalendarFrom.text =
                Utils.formatTime(mFromTimestamp, Utils.DATE_FORMAT_PATTERN_EN1)
        }
    }


    private fun initState() {
        mViewBinding.miHomeRouteAddressView.visibility = View.GONE
        mHistoryDataMapCommon.clearAllMarker()
        setSeekBarMax(0)
    }

    private fun initEven() {
        mViewBinding.vsbMapRouteLine.setOnSeekBarChangeProgressListener(object :
            VerticalTopToBottomSeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(progress: Int) {
                if (mProgress == progress) {
                    return
                }
                mProgress = progress
                mViewBinding.miHomeRouteAddressView.visibility = View.GONE
                mHistoryDataMapCommon.slideChanged(progress)

//                val historyDataBean = mHistoryDataList[progress]
//                val address = historyDataBean.address
//                if (!TextUtils.isEmpty(address)) {
//                    mHistoryDataMapCommon.showInfoWindow(historyDataBean)
//                }
            }

            override fun onStopChanged(progress: Int) {
                mHistoryDataMapCommon.slideStopChanged(progress)
            }
        })

        mViewBinding.rgHistoryRouteMapTrackType.setOnCheckedChangeListener { _, checkedId ->
//            mViewBinding.vsbMapRouteLine.progress = mViewBinding.vsbMapRouteLine.max
            when (checkedId) {
                mViewBinding.rbHistoryRouteMapLine.id -> {
                    MMKVUtil.putInt(MMKVKey.LineSelectPosition, ConstantInt.Line)
                    mHistoryDataMapCommon.addSetLine()
                    if (mHistoryDataList.size > 0) {
//                        mHistoryDataMapCommon.slideStopChanged(mHistoryDataList.size - 1)
                    } else {
                        showToast(R.string.no_data, gravity = Gravity.CENTER)
                    }
                }

                mViewBinding.rbHistoryRouteMapNumber.id -> {
                    MMKVUtil.putInt(MMKVKey.LineSelectPosition, ConstantInt.Point)
                    mHistoryDataMapCommon.addSetNumber()
                    if (mHistoryDataList.size > 0) {
//                        mHistoryDataMapCommon.slideStopChanged(mHistoryDataList.size - 1)
                    } else {
                        showToast(R.string.no_data, gravity = Gravity.CENTER)
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        //续费成功后，不执行
        if (mRechargeBackType == ConstantInt.Type1) {
            return
        }
        getHomeV2Activity()?.apply {
            if (mCurrentShowPetPos == mSelectPetPosition) {
                if (!isSelectCustomDate) {
                    if (mHistoryDataMapCommon.isMapLoadOk()) {
                        get24HourTime()
                        getHistoryDay(mViewBinding.tvHomeRouteCalendarFrom)
                    }
                }
            } else {
                //其他页面是否选择了宠物
                if (!isSelectCustomDate) get24HourTime()
                showPetNameAndHead(mSelectPetPosition)
            }
            checkNotifyLocationState()
        }
    }

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

    override fun liveDataObserve() {
        //更新套餐数据
        XEventBus.observe(this, EventName.RefreshPackage) {
            //监听续费成功
            if (mRechargeBackType == ConstantInt.Type0) {
                mRechargeBackType = ConstantInt.Type1
            }
        }

        mDataDetailViewModel.mHistoryDetailLive.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    setLatLngData(data)
                }
            }, isShowNoDataTip = false)
        }

        //地理反编译成功返回
        mGeoCoderViewModel.mLatLonAddressLiveData.observe(this) {
            val position = mViewBinding.vsbMapRouteLine.progress
            if (mHistoryDataList.size <= position) return@observe
            mHistoryDataList[position].apply {
                //详细位置
                address = it

                val timeString = Utils.formatTime(timeStamp * 1000, Utils.DATE_FORMAT_PATTERN_EN10)
                //更新位置时间
                dayTime = timeString

//                var delay = 500L
//                //第一次延时，等待地图动画执行完成
//                if (isFirst) {
//                    isFirst = false
//                    delay = 1500
//                }
                mViewBinding.root.postDelayed(
                    {
                        mViewBinding.miHomeRouteAddressView.let { mi ->
                            mi.visibility = View.VISIBLE
                            mi.setShowText(timeString, it)
                        }
                    }, 100
                )
            }
        }
    }

    /**
     * 地图加载好了
     */
    private fun mapLoadOk() {
        if (mCurrentShowPetPos == -1) return
        getHomeV2Activity()?.apply {
            showPetNameAndHead(mSelectPetPosition)
        }
    }

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

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

            ViewUtil.instance.selectPetDialogShow(
                mContext,
                mPetList,
                position,
                mViewBinding.ilHomeRoutePetHead.homeDataPetNameSmall,
                mViewBinding.ilHomeRoutePetHead.homeDataPetHeadSmall.appHeadImage
            )

            if (mHistoryDataMapCommon.isMapLoadOk()) {
                getHistoryDay(mViewBinding.tvHomeRouteCalendarFrom)
            }
        }
    }

    private fun setLatLngData(data: MutableList<HistoryDataBean>) {
        viewLifecycleOwner.lifecycleScope.launch {
            mHistoryDataList = data
            getHomeV2Activity()?.getPet(false)?.let {
                mHistoryDataMapCommon.setPetBean(it)
            }

            if (isResumed) {
                getHomeV2Activity()?.getPet()?.let { pet ->
                    if (Util.checkPackageLimit(getHomeV2Activity()!!, pet.deviceId)) {
                        mRechargeBackType = pet.availableOrder
                        mHistoryDataMapCommon.setPetUserLatLng()
                        return@launch
                    }
                }
            }
            if (data.size == 0) {
                mViewBinding.vsbMapRouteLine.visibility = View.GONE
                mHistoryDataMapCommon.setPetUserLatLng()
                return@launch
            }

            mViewBinding.vsbMapRouteLine.visibility = View.VISIBLE
            val max = data.size - 1
            setSeekBarMax(max)

            mHistoryDataMapCommon.setLatLngData(data)
        }
    }

    private fun setSeekBarMax(max: Int) {
        mViewBinding.vsbMapRouteLine.let {
            it.max = max
            //定位中心显示最后一个经纬度
            it.progress = max
        }
    }

    /**
     * cSelectView 当前设置日期的view
     */
    private fun getHistoryDay(cSelectView: TypefaceTextView) {
        mViewBinding.apply {
            mFromTimestamp = Utils.stringToTimestamp(
                tvHomeRouteCalendarFrom.text.toString(), Utils.DATE_FORMAT_PATTERN_EN1
            )
            mToTimestamp = Utils.stringToTimestamp(
                tvHomeRouteCalendarTo.text.toString(), Utils.DATE_FORMAT_PATTERN_EN1
            )
            if (mToTimestamp - mFromTimestamp < 0) {
                checkCorrectDate(cSelectView)
            } else if (mToTimestamp - mFromTimestamp > mOnlySelectDay * 24 * 60 * 60 * 1000) {
                checkCorrectDate(cSelectView)
            }

            getHomeV2Activity()?.getPet()?.apply {
                initState()
                mDataDetailViewModel.getHistoryByDay(
                    getHomeV2Activity()!!, deviceId, mFromTimestamp / 1000, mToTimestamp / 1000
                )
            }
        }
    }

    /**
     * 检测符合的日期
     */
    private fun checkCorrectDate(cSelectView: TypefaceTextView) {
        mViewBinding.apply {
            if (cSelectView == tvHomeRouteCalendarFrom) {
                mToTimestamp = Utils.getAfterHowTimestamp(mFromTimestamp, mOnlySelectDay)
                if (mToTimestamp > mCurrentTimestamp) {
                    mToTimestamp = mCurrentTimestamp
                }
                tvHomeRouteCalendarTo.text = Utils.formatTime(
                    mToTimestamp, Utils.DATE_FORMAT_PATTERN_EN1
                )
                mToCalenderDialog?.setSelectDate(mToTimestamp)
            } else {
                //结束日期小于开始日期，就默认选择结束日期前一天
                mFromTimestamp =
                    if (mFromTimestamp > mToTimestamp) Utils.getBeforeHowTimestamp(mToTimestamp, 1L)
                    else Utils.getBeforeHowTimestamp(mToTimestamp, mOnlySelectDay)
                tvHomeRouteCalendarFrom.text = Utils.formatTime(
                    mFromTimestamp, Utils.DATE_FORMAT_PATTERN_EN1
                )
                mFromCalenderDialog?.setSelectDate(mFromTimestamp)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
//                ilHomeRoutePetHead.ivTopPetBtnSmall -> startActivity(
//                    Intent(
//                        mContext, NotificationV2Activity::class.java
//                    )
//                )
                ilHomeRoutePetHead.homeDataPetNameSmall, ilHomeRoutePetHead.homeDataPetHeadSmall.root -> {
                    getHomeV2Activity()?.let {
                        if (!it.isNotifyRefreshLocation) it.selectPetDialog(false)
                    }
                }

                llHomeRouteCalendarFrom -> {
                    getHomeV2Activity()?.getPet()?.let {
                        //防止执行多次弹窗
                        if (isLimitClick()) {
                            return@apply
                        }
                        if (Util.checkPackageLimit(getHomeV2Activity()!!, it.deviceId)) {
                            mRechargeBackType = it.availableOrder
                            return@apply
                        }
                    }

                    if (null == mFromCalenderDialog) {
                        mFromCalenderDialog = ShowCalenderAndTimeDialog(
                            mContext!!,
                            tvHomeRouteCalendarFrom,
                            object : BaseDialog.OnDialogSelectListener {
                                override fun onSelectClick(dialog: BaseDialog<*>, any: Any) {
                                    mCurrentTimestamp = System.currentTimeMillis()
                                    isSelectCustomDate = true
                                    getHistoryDay(tvHomeRouteCalendarFrom)
                                }
                            },
                            calenderShowTimestamp = mFromTimestamp
                        )
                    }
                    mFromCalenderDialog?.show()
                }

                llHomeRouteCalendarTo -> {
                    getHomeV2Activity()?.getPet()?.let {
                        //防止执行多次弹窗
                        if (isLimitClick()) {
                            return@apply
                        }
                        if (Util.checkPackageLimit(getHomeV2Activity()!!, it.deviceId)) {
                            mRechargeBackType = it.availableOrder
                            return@apply
                        }
                    }
                    if (null == mToCalenderDialog) {
                        mToCalenderDialog = ShowCalenderAndTimeDialog(
                            mContext!!,
                            tvHomeRouteCalendarTo,
                            object : BaseDialog.OnDialogSelectListener {
                                override fun onSelectClick(dialog: BaseDialog<*>, any: Any) {
                                    isSelectCustomDate = true
                                    getHistoryDay(tvHomeRouteCalendarTo)
                                }
                            },
                            calenderShowTimestamp = mToTimestamp
                        )
                    }
                    mToCalenderDialog?.show()
                }

                ivHomeRouteMapTypeBtn -> mHistoryDataMapCommon.switchSatelliteAndNormalMapType()
            }
        }
    }
}