package com.abbidot.tracker.ui.fragment.map.googlemap

import android.animation.ValueAnimator
import android.content.Context
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.widget.MapDeviceNetView
import com.abbidot.tracker.widget.MapMarkerInfoView
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Polyline
import com.google.android.gms.maps.model.PolylineOptions
import kotlin.math.pow

/**
 *Created  by .yzq on 2022/1/13/013.
 * @link
 * @description:首页map谷歌地图
 */
class HomeMapGoogleMapFragment : BaseGoogleMapFragment() {

    private val mGeoCoderViewModel: GeoCoderViewModel by viewModels()

    private lateinit var mMarkerInfoView: MapMarkerInfoView
    private lateinit var mMapDeviceNetView: MapDeviceNetView

    //宠物当前反地理位置信息
    var mDecPetAddressData: HistoryDataBean? = null
    private var mMapDeviceBean: MapDeviceBean? = null
    private lateinit var mMapLoadOk: () -> Unit

    //启动动画移动地图摄像机
    private var isMoveCamera = true
    private var mPolyline: Polyline? = null
    private var mRippleCircle: Circle? = null
    private var mValueAnimator: ValueAnimator? = null

    //    private var mAnimatorDuration=2000L
    private var mRippleCirclePercent = 0.0
    private var mRippleCircleRadius = 200

    companion object {
        @JvmStatic
        fun newInstance(
            context: Context,
            markerInfoView: MapMarkerInfoView,
            mapDeviceNetView: MapDeviceNetView,
            mapLoadOk: () -> Unit
        ) = HomeMapGoogleMapFragment().apply {
            mContext = context
            mMarkerInfoView = markerInfoView
            mMapDeviceNetView = mapDeviceNetView
            mMapLoadOk = mapLoadOk
        }
    }

    fun setMapDeviceBean(mapDeviceBean: MapDeviceBean?) {
        mMapDeviceBean = mapDeviceBean
    }

    override fun liveDataObserve() {
        //反地理编码成功返回
        mGeoCoderViewModel.mLatLonAddressLiveData.observe(viewLifecycleOwner) {
            //保存地理信息,方便传参给导航页面
            if (null == mDecPetAddressData) mDecPetAddressData = HistoryDataBean()

            mMapDeviceBean?.apply {
//                val timeString = String.format(
//                    getString(R.string.map_current_update_time),
//                    DateUtils.getRelativeTimeSpanString(
//                        updateTime * 1000
//                    )
//                )
                val timeString =
                    Utils.formatTime(latLonUpdateTime * 1000, Utils.DATE_FORMAT_PATTERN_EN6)
                mDecPetAddressData?.let { history ->
                    //更新位置时间
                    history.dayTime = timeString
                    //详细位置
                    history.address = it
                    //传递位置信息给InfoWindowAdapter窗口
//                    mMarker?.tag = history

//                    showMarkerInfoWindow(history)
                    ViewUtil.instance.viewShow(mMarkerInfoView)
                    mMarkerInfoView.setShowText(timeString, it)
                }
            }
        }
    }

    override fun onMapLoadOk(googleMap: GoogleMap) {
//        initFenceList()
        //设置自定义头部地点布局
        mGoogleMap?.apply {
            setOnCameraMoveListener {
                if (mMarkerInfoView.isVisible) setMarkerInfoViewOffset()
            }
            getLastLocation()
        }

        //变量是否初始化
        if (::mMapLoadOk.isInitialized) mMapLoadOk()
    }


    override fun onRefreshPetCurrentLocationOk(googleMap: GoogleMap) {
        if (null == mMarker) return
        else startReverseGeocode()
    }

    /**
     * 刚开始的反编译地理位置
     */
    private fun startReverseGeocode() {
        mMapDeviceBean?.apply {
            mGeoCoderViewModel.getLatLonAddress(latitude, longitude, false)
            setMarkerInfoViewOffset()

//            val time = System.currentTimeMillis() - mReverseGeocodeTime
//            //判断有没有超过设置的刷新时间
//            if (time > mMapFragment.mMapDeviceBean!!.gnssInterval * 60 * 1000) {
//                mGeoCoderViewModel.getLatLonAddress(mMapFragment.mMapDeviceBean!!.latitude,
//                        mMapFragment.mMapDeviceBean!!.longitude)
//            } else {
//                //传递位置信息给InfoWindowAdapter窗口
//                mMarker?.tag = mMapFragment.mHistoryDataBean
//                showMarkerInfoWindow()
//            }
//            }
        }
    }

    fun setMarkerInfoViewOffset() {
        mPetLatLng?.apply {
            setMarkerInfoViewOffset(mMarkerInfoView, LatLng(latitude, longitude))
            setMapNetTypeViewOffset(mMapDeviceNetView, LatLng(latitude, longitude))
        }
    }

    /**
     * 点击大头针开始更新反地理编码
     */
    private fun reverseGeocode() {
//        val time = System.currentTimeMillis() - mReverseGeocodeTime
        //判断有没有超过设置的刷新时间
//        if (time > mMapFragment.mMapDeviceBean!!.gnssInterval * 60 * 1000) {
//            mGeoCoderViewModel.getLatLonAddress(mMapFragment.mMapDeviceBean!!.latitude,
//                    mMapFragment.mMapDeviceBean!!.longitude)
//        }
    }

    /**
     * 计算用户和宠物的距离
     */
    fun getUserAndPetDistance(): Double {
        var distance = 0.0
        mUserLatLng?.apply {
            mPetLatLng?.let {
                distance =
                    Util.measureLatLonDistance(latitude, longitude, it.latitude, it.longitude)
            }
        }
        return distance
    }

    /**
     * 画用户和宠物之间的虚线
     */
    private fun addUserAndPetLine(petLatLng: LatLng) {
        mUserLatLng?.apply {
            mGoogleMap?.let {
                if (null == mPolyline) {
                    val polylineOptions =
                        PolylineOptions().clickable(false).width(AppUtils.dpToPx(1.5f))
                            .color(ContextCompat.getColor(mContext!!, R.color.blue_color9))
                            .geodesic(false)
                    mPolyline = it.addPolyline(polylineOptions)
                    mPolyline?.pattern = getDashedPatternStyle(18f)
                }
                mPolyline?.let { pLine ->
                    val latList = mutableListOf<LatLng>()
                    latList.add(petLatLng)
                    latList.add(this)
                    pLine.points = latList
                }
            }
        }
    }

    /**
     * 初始化并添加水波纹圆
     */
    private fun addRippleCircle() {
        mPetLatLng?.apply {
            mGoogleMap?.let {
                if (null == mRippleCircle) {
                    mRippleCircle = it.addCircle(
                        CircleOptions().center(this)
                            .radius(mRippleCircleRadius * mRippleCirclePercent)
                            .strokeWidth(AppUtils.dpToPx(2).toFloat())
                            .fillColor(ContextCompat.getColor(mContext!!, R.color.black10))
                            .strokeColor(ContextCompat.getColor(mContext!!, R.color.black10))
                    )

                    setRippleCircleAnim()
                }
            }
        }
    }

    /**
     * 设置水波纹动画
     */
    private fun setRippleCircleAnim() {
        if (null == mValueAnimator) {
            mValueAnimator = ViewUtil.instance.setValueAnimator(
                0.0, 100.0, 1500, LinearInterpolator()
            ) {
                mRippleCirclePercent = it.animatedValue as Float / 100.0
                mRippleCircle?.apply {
                    mPetLatLng?.let { petLatLng ->
                        center = petLatLng
                        radius = mRippleCircleRadius * mRippleCirclePercent
                    }
                }
            }?.apply {
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
            }
        }
    }

    /**
     * 画线
     */
    fun addLine(latLng: LatLng) {
//        addPolyline(mGoogleMap!!, latLng)
//        addUserAndPetLine(latLng)
        refreshPetCurrentLocation(latLng, needMoveCamera = isMoveCamera)

//        mRippleCircle?.apply {
//            //一像素对应几米
//            val pxDis = 2.0.pow(15.5 - getGoogleMapZoom())
//            mRippleCircleRadius = (pxDis * 150).toInt()
//            fillColor = (ContextCompat.getColor(mContext!!, R.color.select_color5))
//            strokeColor = (ContextCompat.getColor(mContext!!, R.color.select_color5))
//            mValueAnimator?.duration = 2000
//        }
    }

    /**
     * 画多条线
     */
    fun addLines(trackList: MutableList<HistoryDataBean>) {
        val latLngList = mutableListOf<LatLng>()
        for (i in 0 until trackList.size) {
            trackList[i].apply {
                val latLng = LatLng(latitude, longitude)
                latLngList.add(latLng)
                if (i == trackList.size - 1) {
//                    addUserAndPetLine(latLng)
                    refreshPetCurrentLocation(latLng, needMoveCamera = isMoveCamera)
                }
            }
        }
//        addPolyLines(mGoogleMap!!, latLngList)
    }

    /**
     * 开始水波纹动画
     */
    fun startRippleCircleAnim() {
        mPetLatLng?.apply {
            //一像素对应几米
            val pxDis = 2.0.pow(15.5 - getGoogleMapZoom())
            mRippleCircleRadius = (pxDis * 150).toInt()
//            addUserAndPetLine(this)
            addRippleCircle()
        }
    }

    /**
     * 直播开始之后，改变绿色波纹动画
     */
    fun greenRippleCircleAnim() {
        mRippleCircle?.apply {
            //一像素对应几米
            val pxDis = 2.0.pow(15.5 - getGoogleMapZoom())
            mRippleCircleRadius = (pxDis * 150).toInt()
            fillColor = (ContextCompat.getColor(mContext!!, R.color.select_color5))
            strokeColor = (ContextCompat.getColor(mContext!!, R.color.select_color5))
            mValueAnimator?.duration = 2000
        }
    }

    override fun onDetach() {
        super.onDetach()
        mValueAnimator?.cancel()
    }
}