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

import android.animation.ValueAnimator
import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
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.constant.ConstantInt
import com.abbidot.tracker.databinding.LayoutPetLocationInfoBinding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
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.Marker
import com.google.android.gms.maps.model.Polyline
import kotlin.math.pow

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

    private val mGeoCoderViewModel: GeoCoderViewModel by viewModels()

    private lateinit var mPetLocationLayoutBinding: LayoutPetLocationInfoBinding
    private lateinit var mDeviceBatteryLayout: ViewGroup

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

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

    private var mRippleCirclePercent = 0.0
    private var mRippleCircleRadius = 200

    //是否是地图摄像头移动了
    private var isMapCameraMove = false
    private var mPetAddressTimeFormat = Utils.DATE_FORMAT_PATTERN_EN11

    //是否需要反编译地理位置
    private var isReverseGeocode = false

    companion object {
        @JvmStatic
        fun newInstance(
            context: Context,
            locationLayoutViewBinding: LayoutPetLocationInfoBinding,
            deviceBatteryLayout: ViewGroup,
            petAddressTimeFormat: String,
            isGeocode: Boolean,
            mapLoadOk: () -> Unit
        ) = HomeMapGoogleMapFragmentV3().apply {
            mContext = context
            mDeviceBatteryLayout = deviceBatteryLayout
            mPetLocationLayoutBinding = locationLayoutViewBinding
            isReverseGeocode = isGeocode
            mPetAddressTimeFormat = petAddressTimeFormat
            mMapLoadOk = mapLoadOk
        }
    }

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

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

            mMapDeviceBean?.apply {
                val timeString = Utils.formatTime(latLonUpdateTime * 1000, mPetAddressTimeFormat)
                mDecPetAddressData?.let { history ->
                    //更新位置时间
                    history.dayTime = timeString
                    //详细位置
                    history.address = it
                    //传递位置信息给InfoWindowAdapter窗口
//                    mMarker?.tag = history

//                    showMarkerInfoWindow(history)
                    val address =
                        if (inWifiZone == ConstantInt.Type1 && !TextUtils.isEmpty(wifiZoneName)) {
                            "$wifiZoneName · $it"
                        } else {
                            String.format(mContext!!.getString(R.string.txt_near), it)
                        }
                    ViewUtil.instance.viewShow(mPetLocationLayoutBinding.root)
                    mPetLocationLayoutBinding.let { layout ->
                        layout.tvPetLocationReverseGeocode.text = address
                        layout.tvPetLocationUpdateTime.text = timeString
                        layout.tvPetLocationUpdateTimeFormat.visibility =
                            if (powerSwitch == ConstantInt.Type2) View.GONE
                            else {
                                if (Util.isTimeoutReport(updateTime, gnssInterval)) {
                                    layout.tvPetLocationUpdateTimeFormat.text = String.format(
                                        getString(R.string.txt_location_ago),
                                        Utils.getTimeDifference(
                                            updateTime * 1000, System.currentTimeMillis()
                                        )
                                    )
                                    View.VISIBLE
                                } else View.GONE
                            }
                    }
                }
            }
        }
    }

    override fun onMapLoadOk(googleMap: GoogleMap) {
        //设置自定义头部地点布局
        mGoogleMap?.apply {
            setOnCameraIdleListener {
                if (isMapCameraMove) {
                    isMapCameraMove = false
                } else {
                    setMarkerInfoViewOffset()
                }
            }
            setOnCameraMoveListener {
                //监听地图放大缩小操作
                if (getGoogleMapZoom() != cameraPosition.zoom) {
                    setGoogleMapZoom(cameraPosition.zoom)
                }
                isMapCameraMove = true
                setMarkerInfoViewOffset()
            }

            setOnMarkerClickListener(object : GoogleMap.OnMarkerClickListener {
                override fun onMarkerClick(marker: Marker): Boolean {
                    if (marker == mMarker) {
                        mMapDeviceBean?.let {
                            if (it.canShowBattery) {
                                mDeviceBatteryLayout.visibility =
                                    if (mDeviceBatteryLayout.isVisible) {
                                        it.isCloseBattery = true
                                        View.GONE
                                    } else {
                                        it.isCloseBattery = false
                                        View.VISIBLE
                                    }
                            }
                        }
                        return true
                    }
                    return false
                }
            })
            getLastLocation()
        }

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

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

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

    fun setMarkerInfoViewOffset() {
        mPetLatLng?.apply {
            mMapDeviceBean?.let {
                setMapDeviceBatteryOffset(
                    mDeviceBatteryLayout, LatLng(latitude, longitude), it
                )
            }
        }
    }

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

    /**
     * 画用户和宠物之间的虚线
     */
    fun addUserAndPetLine() {
        mGoogleMap?.apply {
            mUserLatLng?.let { u ->
                mPetLatLng?.let { p ->
                    mUserAndPetLine?.remove()
                    getPolylineOptions(1.5f, R.color.blue_color9).let {
                        it.add(toGCJ02LatLon(p))
                        it.add(toGCJ02LatLon(u))
                        mUserAndPetLine = addPolyline(it)
                    }
                    mUserAndPetLine?.pattern = getDashedPatternStyle(18f)
                }
            }
        }
    }

    fun removeUserAndPetLine() {
        mUserAndPetLine?.remove()
    }

    /**
     * 初始化并添加水波纹圆
     */
    private fun addRippleCircle() {
        mPetLatLng?.apply {
            mGoogleMap?.let {
                if (null == mRippleCircle) {
                    mRippleCircle = it.addCircle(
                        CircleOptions().center(toGCJ02LatLon(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 = toGCJ02LatLon(petLatLng)
                        radius = mRippleCircleRadius * mRippleCirclePercent
                    }
                }
            }?.apply {
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
            }
        } else {
            mValueAnimator?.apply {
                if (!isRunning) start()
            }
        }
    }

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

//        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(toGCJ02LatLon(latLng))
                if (i == trackList.size - 1) {
//                    addUserAndPetLine(latLng)
                    refreshPetCurrentLocation(latLng, needMoveCamera = isMoveCamera)
                    isMoveCamera = false
                }
            }
        }
//        addPolyLines(mGoogleMap!!, latLngList)
    }

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

    /**
     * 直播开始之后，改变绿色波纹动画
     */
    fun greenRippleCircleAnim() {
        if (null == mRippleCircle) addRippleCircle()
        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 clearRippleCircleAnim() {
        mValueAnimator?.cancel()
        mRippleCircle?.remove()
        mRippleCircle = null
    }

    override fun onDetach() {
        super.onDetach()
        clearRippleCircleAnim()
    }
}