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

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Typeface
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.view.isVisible
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.tracker.R
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.widget.MapMarkerInfoView
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

/**
 *Created  by .yzq on 2022/1/13/013.
 * @link
 * @description:历史记录map谷歌地图
 */
class HistoryDataGoogleMapFragment : BaseGoogleMapFragment() {

    //    private val mScreenshotsViewModel: ScreenshotsViewModel by viewModels()
    private lateinit var mGeoCoderViewModel: GeoCoderViewModel
    private lateinit var mMarkerInfoView: MapMarkerInfoView
    private lateinit var mVerticalTopToBottomSeekBar: AppCompatSeekBar

    private val mMarkerOptions = MarkerOptions()
    private lateinit var mPetIconDescriptor: BitmapDescriptor

    private val mLatLngList = mutableListOf<LatLng>()

    //字体
    private var mTypeface = Typeface.DEFAULT

    //是否地图截屏
    private var isMapSnapshot = true
    private lateinit var mMapLoadOk: () -> Unit

    private var mPetBean: PetBean? = null
    private var mCurLatLng: LatLng? = null

    companion object {
        @JvmStatic
        fun newInstance(
            context: Context,
            markerInfoView: MapMarkerInfoView,
            geoCoderViewModel: GeoCoderViewModel,
            verticalTopToBottomSeekBar: AppCompatSeekBar,
            mapLoadOk: () -> Unit
        ) = HistoryDataGoogleMapFragment().apply {
            mContext = context
            mGeoCoderViewModel = geoCoderViewModel
            mVerticalTopToBottomSeekBar = verticalTopToBottomSeekBar
            mMarkerInfoView = markerInfoView
            mMapLoadOk = mapLoadOk
        }
    }

    override fun initData() {
        super.initData()
        mTypeface =
            ViewUtil.instance.setTypeface(mContext!!, getString(R.string.number_din_cond_font))
    }

    override fun onMapLoadOk(googleMap: GoogleMap) {
//        val mutableList = mLatLngList
//        mutableList.add(LatLng(22.5654646, 113.9514812))
//        mutableList.add(LatLng(22.5666646, 113.9524812))
//        mutableList.add(LatLng(22.5676646, 113.9525812))
//        mutableList.add(LatLng(22.5687646, 113.9525912))
//        mutableList.add(LatLng(22.5698646, 113.9522912))
//        mutableList.add(LatLng(22.5659646, 113.9530112))
//        mutableList.add(LatLng(22.5660646, 113.9545112))
//        mutableList.add(LatLng(22.5670646, 113.9555112))
//        mutableList.add(LatLng(22.5680646, 113.9565112))
//        mutableList.add(LatLng(22.5690646, 113.9575112))
//        mutableList.add(LatLng(22.5690646, 113.9585112))
//        mutableList.add(LatLng(22.5690646, 113.9596112))
//        mutableList.add(LatLng(22.5700646, 113.9626112))
//        mutableList.add(LatLng(22.5720646, 113.9656112))
//        mutableList.add(LatLng(22.5760646, 113.9666112))

        //点击地图任意地方都不消失自定义头部地点布局
        googleMap.apply {
            setOnCameraMoveListener {
                //监听地图放大缩小操作
                if (getGoogleMapZoom() != cameraPosition.zoom) {
                    setGoogleMapZoom(cameraPosition.zoom)
                }
                resetMarkerInfoViewOffset()
            }
            setOnMarkerClickListener { m ->
                //点击数字大头针回到该位置
                if (m != mMarker) {
                    val index = m.tag
                    if (index is Int) {
                        mVerticalTopToBottomSeekBar.progress = index
                        mMarker?.let {
                            it.position = m.position
                        }
                        slideStopChanged(index)
                    }
                    true
                } else false
            }
        }

        getLastLocation()

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

    fun resetMarkerInfoViewOffset() {
        mCurLatLng?.let {
            if (mMarkerInfoView.isVisible) setMarkerInfoViewOffset(mMarkerInfoView, it)
        }
    }

    suspend fun setPetBean(petBean: PetBean) {
        if (petBean == mPetBean) {
            return
        }
        mPetBean = petBean
//        lifecycleScope.launch {
//        }
        try {
            mPetBean?.apply {
                var bitmap = GoogleBitmapHelper.headToBitmap(
                    mContext!!, R.drawable.pic_map_gps_avatar, imgurl, petType
                )
                if (null == bitmap) bitmap = BitmapFactory.decodeResource(
                    mContext!!.resources, R.drawable.icon_location_svg
                )
                mPetIconDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap!!)
                mMarker?.setIcon(mPetIconDescriptor)
            }
        } catch (e: Exception) {
            LogUtil.e("setPetBean 异常了$e")
        }
    }

    /**
     * 设置经纬度数据
     */
    fun setLatLngData(data: MutableList<HistoryDataBean>) {
        mGoogleMap?.clear()

        if (data.size == 0) return
        mLatLngList.clear()
        var maxLat = data[0].latitude
        var maxLon = data[0].longitude
        var minLat = data[0].latitude
        var minLon = data[0].longitude

        data.forEach { historyDataBean ->
            historyDataBean.apply {
                if (maxLat < latitude) maxLat = latitude
                if (maxLon < longitude) maxLon = longitude
                if (minLat > latitude) minLat = latitude
                if (minLon > longitude) minLon = longitude
                val latLng = LatLng(latitude, longitude)
                mLatLngList.add(latLng)
            }
        }

        //根据经纬度来设置缩放级别
        setLatLngZoom(
            mContext!!, AppUtils.dpToPx(50), LatLng(minLat, minLon), LatLng(maxLat, maxLon)
        )

        val maxIndex = data.size - 1
        mCurLatLng = mLatLngList[maxIndex]

        val type = MMKVUtil.getInt(MMKVKey.LineSelectPosition, ConstantInt.Line)
        if (type == ConstantInt.Line) {
            addSetLine()
        } else {
            addSetNumber()
        }

        mGeoCoderViewModel.getLatLonAddress(
            mLatLngList[maxIndex].latitude, mLatLngList[maxIndex].longitude, false
        )
        setMarkerInfoViewOffset(mMarkerInfoView, mLatLngList[maxIndex])
    }

    /**
     * 滑动改变
     */
    fun slideChanged(progress: Int) {
        if (progress < mLatLngList.size) setPetMarkerLatLng(mLatLngList[progress])
    }

    /**
     * 停止滑动
     */
    fun slideStopChanged(progress: Int) {
        if (mLatLngList.size > 0) {
            moveCameraLocation(
                mLatLngList[progress].latitude, mLatLngList[progress].longitude, true
            )
            mGeoCoderViewModel.getLatLonAddress(
                mLatLngList[progress].latitude, mLatLngList[progress].longitude, false
            )

            mCurLatLng = mLatLngList[progress]
            setMarkerInfoViewOffset(mMarkerInfoView, mLatLngList[progress])
        }
    }

    override fun clearAllMarker() {
        super.clearAllMarker()
        mLatLngList.clear()
    }

    /**
     * 画线
     */
    fun addSetLine(isMoveCamera: Boolean = true) {
        val size = mLatLngList.size
        LogUtil.e("画线点有 $size 个")
        if (size == 0) return
        mGoogleMap?.let {
            it.clear()

            if (isMoveCamera) moveCameraUpdate(mLatLngList[size - 1])

            addSinglePolyline(it, mLatLngList)

//            refreshPetCurrentLocation(
//                mLatLngList[size - 1], needMoveCamera = false, isAnimMoveCamera = false
//            )

            //设置宠物头像和经纬度
            if (null == mCurLatLng) setPetMarkerLatLng(mLatLngList[size - 1])
            else setPetMarkerLatLng(mCurLatLng!!)
        }
    }

    /**
     * 设置显示数字
     */
    fun addSetNumber(isMoveCamera: Boolean = true) {
        val size = mLatLngList.size
        LogUtil.e("轨迹谷歌地图设置显示数字$size,经纬度点")
        if (size == 0) return
        mGoogleMap?.let {
            it.clear()

            if (isMoveCamera) moveCameraUpdate(mLatLngList[size - 1])

//            refreshPetCurrentLocation(
//                mLatLngList[size - 1], needMoveCamera = false, isAnimMoveCamera = false
//            )

            for (i in 0 until mLatLngList.size) {
                val newLatLng = toGCJ02LatLon(mLatLngList[i])
                val numberMarker = MarkerOptions().position(newLatLng).icon(
                    BitmapDescriptorFactory.fromBitmap(
                        GoogleBitmapHelper.imageUpNumberBitmap(
                            mContext!!,
                            R.drawable.pic_history_location,
                            (i + 1).toString(),
                            mTypeface
                        )
                    )
                )
                it.addMarker(numberMarker)?.apply {
                    tag = i
                }
            }

            //设置宠物头像和经纬度
            if (null == mCurLatLng) setPetMarkerLatLng(mLatLngList[size - 1])
            else setPetMarkerLatLng(mCurLatLng!!)
        }
    }

    /**
     * 设置宠物Marker经纬度
     */
    fun setPetMarkerLatLng(latLng: LatLng) {
        if (::mPetIconDescriptor.isInitialized) {
            mGoogleMap?.apply {
                val newLatLng = toGCJ02LatLon(latLng)
                mMarkerOptions.position(newLatLng).icon(mPetIconDescriptor)
                mMarker?.remove()
                mMarker = addMarker(mMarkerOptions)
                //显示最上面，层级最高
                mMarker?.zIndex = 1f
                setUserMarker()
            }
        }
    }
}