package com.base.locationsharewhite.ui.locationmap

import android.graphics.Color
import android.view.LayoutInflater
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.locationsharewhite.R
import com.base.locationsharewhite.databinding.ActivityLocationMapBinding
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.map.MapUtils.addLocationMarker
import com.base.locationsharewhite.map.MapUtils.cameraMovePointsBounds
import com.base.locationsharewhite.map.MapUtils.getLastKnowLatLng
import com.base.locationsharewhite.ui.views.DialogView.showMapTypeDialog
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.BitmapUtils
import com.base.locationsharewhite.utils.LogEx
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch


class LocationMapActivity : BaseActivity<ActivityLocationMapBinding>(), OnMapReadyCallback {

    private val TAG = "LocationMapActivity"
    private var map: GoogleMap? = null

    override val binding: ActivityLocationMapBinding by lazy {
        ActivityLocationMapBinding.inflate(layoutInflater)
    }

    private var myMarker: Marker? = null
    private var friendMarker: Marker? = null


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
//        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())


        val mapFragment =
            supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.ivFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.ivChangeMapType.setOnClickListener {
            map?.let { showMapTypeDialog(it) }
        }
        binding.ivLocation.setOnClickListener {
            val i = 2
            if (i == 2) {
                val chunxilu = LatLng(30.655782251943407, 104.07701072527895)
                upDateMeAndFriendLocation(chunxilu)
            } else {
                resetMyLocation()
            }

        }
    }

    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap


        val sydney = LatLng(-33.87365, 151.20689)
//        showMeAndFriendLocation(sydney)

        val chunxilu = LatLng(30.655782251943407, 104.07701072527895)
        initMyAndFriendLocation(chunxilu)

        sharingLocationJob()
    }

    private fun resetMyLocation() {
        val myLatLng: LatLng = getLastKnowLatLng()
        myMarker?.position = myLatLng
        map?.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 15f))
    }

    private fun initMyAndFriendLocation(friendLatLng: LatLng) {

        val myLatLng: LatLng = getLastKnowLatLng()
        LogEx.logDebug(TAG, "getLastKnowLocation ${myLatLng.latitude} ${myLatLng.longitude}")

        val myAvatar = LayoutInflater.from(this).inflate(R.layout.avatar_me, null)
        val friendAvatar = LayoutInflater.from(this).inflate(R.layout.avatar_friend, null)

        myMarker = map?.addLocationMarker(myAvatar, myLatLng, "my")
        friendMarker = map?.addLocationMarker(friendAvatar, friendLatLng, "friend")

        val padding = resources.getDimensionPixelOffset(R.dimen.dp_150)
        map?.cameraMovePointsBounds(myLatLng, friendLatLng, padding)

//        val list = arrayListOf<LatLng>()
//        list.addAll(friendTestLine)
//        list.add(friendLatLng)
//        addFriendPolyline(list)
    }

    private fun upDateMeAndFriendLocation(friendLatLng: LatLng) {
        val myLatLng: LatLng = getLastKnowLatLng()
        myMarker?.position = myLatLng
        friendMarker?.position = friendLatLng
        val padding = resources.getDimensionPixelOffset(R.dimen.dp_150)
        map?.cameraMovePointsBounds(myLatLng, friendLatLng, padding)
    }


    val friendTestLine = listOf(
        LatLng(30.65988197028939, 104.07775588286886),//總府皇冠假日酒店
        LatLng(30.658174607262318, 104.06581096754789),//天府广场
        LatLng(30.6531557462031, 104.06660595172475),//航天科技大廈
        LatLng(30.64867742925485, 104.06548317653692),//錦江賓館
        LatLng(30.654908885860806, 104.08053620625755),//ifs
    )

    fun rotateMarker() {

        val myAvatar = LayoutInflater.from(this).inflate(R.layout.avatar_me, null)

        val myPair: LatLng = getLastKnowLatLng()
        val bitmapDescriptor = BitmapUtils.getBitmapDescriptorFromLayoutResId(myAvatar)

        val marker: Marker? = map?.addMarker(
            MarkerOptions()
                .icon(bitmapDescriptor)
                .position(myPair)
                .anchor(0.5f, 0.5f) // 设置锚点为中心
                .rotation(90.0f) // 设置旋转角度
                .flat(true)
        ) // 设置为平面Marker

        lifecycleScope.launch {
            for (i in 0..360) {
                marker?.rotation = i.toFloat()
                delay(200)
            }
        }
    }

    fun addFriendPolyline(list: List<LatLng>) {
        map?.addPolyline(PolylineOptions().apply {
            list.forEach { add(it) }
            width(5.toFloat())
            color(Color.BLUE)
            geodesic(true)
            clickable(true)
        })
    }


    private var sharingJob: Job? = null
    fun sharingLocationJob() {
        if (sharingJob == null) {

            myMarker ?: return
            friendMarker ?: return

            var i = 0f
            var j = 0f
            sharingJob = lifecycleScope.launch {
                while (isActive) {
                    i += 0.001f
                    j += 0.001f

                    val myLatLng = getLastKnowLatLng()
                    myMarker?.position = myLatLng
                    //上传我的位置,获取friend位置
                    val friendLatLng = LatLng(30.655782251943407 + i, 104.07701072527895 + j)
                    friendMarker?.position = friendLatLng

                    delay(1 * 1000L)
                }
            }
        }
    }

    private fun cancelSharingJob() {
        sharingJob?.cancel()
        sharingJob = null
    }

    override fun onPause() {
        super.onPause()
        cancelSharingJob()
    }

}