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

import android.content.Context
import android.graphics.Typeface
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.MMKVKey
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.constant.ConstantInt
import com.abbidot.tracker.ui.fragment.map.googlemap.GoogleBitmapHelper
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.BitmapDescriptor
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Created  by .yzq on 2022/6/28/028.
 * @link
 * @description:
 */
class HistoryDataBaiduMapFragment : BaseBaiduMapFragment() {

    //    private val mScreenshotsViewModel: ScreenshotsViewModel by viewModels()
    private lateinit var mGeoCoderViewModel: GeoCoderViewModel

    //    private lateinit var mHistoryDataActivity: HistoryDataActivity
    private var mLatLngList = mutableListOf<LatLng>()

    private var mPetIconDescriptor: BitmapDescriptor? = null

    private lateinit var mMarkerOptions: MarkerOptions

    //字体
    private var mTypeface = Typeface.DEFAULT

    //是否地图截屏
    private var isMapSnapshot = true

    private lateinit var mMapLoadOk: () -> Unit

    companion object {
        @JvmStatic
        fun newInstance(
            context: Context, geoCoderViewModel: GeoCoderViewModel, mapLoadOk: () -> Unit
        ) = HistoryDataBaiduMapFragment().apply {
            mContext = context
            mGeoCoderViewModel = geoCoderViewModel
            mMapLoadOk = mapLoadOk
        }
    }

    override fun initData() {
//        mHistoryDataActivity = mActivity as HistoryDataActivity
        super.initData()

        mTypeface =
            ViewUtil.instance.setTypeface(mContext!!, getString(R.string.number_din_cond_font))
    }

    override fun onMapLoadOk(baiduMap: BaiduMap) {
//        val today = Utils.getCurrentTime(Utils.DATE_FORMAT_PATTERN)
//        mHistoryDataActivity.mDataDetailViewModel.getHistoryByDay(
//            mHistoryDataActivity, mHistoryDataActivity.mPet.deviceId, today
//        )
        //变量是否初始化
        if (::mMapLoadOk.isInitialized) mMapLoadOk()
    }

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

        if (data.size == 0) return

        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 convertLonLat = getBaiduMapLatLng(latitude, longitude)
                mLatLngList.add(convertLonLat)
            }
        }

        val zoom = getDistanceZoom(LatLng(minLat, minLon), LatLng(maxLat, maxLon))
        LogUtil.e("百度地图zoom==$zoom")
        setBaiduMapZoom(zoom + 1)

        val maxIndex = data.size - 1
        mGeoCoderViewModel.getLatLonAddress(
            mLatLngList[maxIndex].latitude, mLatLngList[maxIndex].longitude, false
        )
        val type = MMKVUtil.getInt(MMKVKey.LineSelectPosition, ConstantInt.Line)
        if (type == ConstantInt.Line) {
            addSetLine()
        } else {
            addSetNumber()
        }
    }


    /**
     * 滑动改变
     */
    fun slideChanged(progress: Int) {
        mMarkerOptions = MarkerOptions().position(mLatLngList[progress]).icon(mPetIconDescriptor)
        mMarker?.remove()
        mMarker = mBaiduMap!!.addOverlay(mMarkerOptions)
    }

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

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

    /**
     * 画线
     */
    fun addSetLine() {
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                getPetIcon()
            }
            val size = mLatLngList.size
            if (size == 0) return@launch
            mBaiduMap?.let {
                it.clear()
                moveCameraLocation(
                    mLatLngList[size - 1].latitude,
                    mLatLngList[size - 1].longitude,
                    needConvertGCJ02 = false
                )
                addPolyline(it, mLatLngList, false, startCapImageRes = 0)

                mMarkerOptions =
                    MarkerOptions().position(mLatLngList[size - 1]).icon(mPetIconDescriptor)
                mMarker?.remove()
                mMarker = it.addOverlay(mMarkerOptions)

                mapSnapshot()
            }
        }
    }

    /**
     * 设置显示数字
     */
    fun addSetNumber() {
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                getPetIcon()
            }
            val size = mLatLngList.size
            if (size == 0) return@launch
            mBaiduMap?.let {
                it.clear()

                moveCameraLocation(
                    mLatLngList[size - 1].latitude,
                    mLatLngList[size - 1].longitude,
                    needConvertGCJ02 = false
                )

                for (i in 0 until mLatLngList.size) {
                    it.addOverlay(
                        MarkerOptions().position(mLatLngList[i]).icon(
                            BitmapDescriptorFactory.fromBitmap(
                                GoogleBitmapHelper.imageUpNumberBitmap(
                                    mContext!!,
                                    R.drawable.pic_history_location,
                                    (i + 1).toString(),
                                    mTypeface
                                )
                            )
                        )
                    )
                }
                mMarkerOptions =
                    MarkerOptions().position(mLatLngList[size - 1]).icon(mPetIconDescriptor)
                mMarker?.remove()
                mMarker = it.addOverlay(mMarkerOptions)

                mapSnapshot()
            }
        }
    }

    /**
     * 获取宠物头像
     */
    private suspend fun getPetIcon() {
        if (null == mPetIconDescriptor) {
//            val bitmap = ImageUtil.getImageBitmapByUrl(mContext!!, mHistoryDataActivity.mPet.imgurl)
//            mPetIconDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap)
//            bitmap.recycle()
            mPetIconDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.pic_avatar_df)
        }
    }

    /**
     * 截屏
     */
    private fun mapSnapshot() {
        if (isMapSnapshot) {
            isMapSnapshot = false
//            mHistoryDataActivity.mTopBar?.postDelayed({
//                if (mHistoryDataActivity.isFrontRunning) {
//                    mScreenshotsViewModel.getHistoryDataBaiduMapSnapshotImage(
//                        mContext!!, mBaiduMap!!, mHistoryDataActivity.mPet.deviceId
//                    )
//                }
//            }, 1000)
        }
    }
}