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

import android.content.Context
import android.graphics.Point
import android.location.Location
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.deprecated.ui.activity.profile.FencesAddActivity
import com.abbidot.tracker.ui.common.map.FencesMapCommon
import com.abbidot.tracker.ui.fragment.map.googlemap.BaseGoogleMapFragment
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.widget.FencesPolygonView
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.LatLng
import com.mapbox.search.ui.view.SearchResultsView
import com.qmuiteam.qmui.util.QMUIDisplayHelper

/**
 *Created  by .yzq on 2022/1/13/013.
 * @link
 * @description:添加围栏map谷歌地图
 */
class FencesAddGoogleMapFragment : BaseGoogleMapFragment() {

    var mCenterLatLng: LatLng? = null
    private var mEndLatLng: LatLng? = null

    var mRectALatLng: LatLng? = null
    var mRectBLatLng: LatLng? = null
    var mRectCLatLng: LatLng? = null
    var mRectDLatLng: LatLng? = null

    private var mOnActivityCallBack: FencesMapCommon.OnActivityCallBack? = null

    private lateinit var mSearchResultsView: SearchResultsView

    //编辑第一次不用计算测量距离
    private var isEditFirst = true

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = FencesAddGoogleMapFragment().apply {
            mContext = context
        }
    }

    override fun onMapLoadOk(googleMap: GoogleMap) {
        val fencesAddActivity = mActivity as FencesAddActivity
        //监听摄像机移动中心点,摄像机移动结束时的回调接口。
        mGoogleMap?.setOnCameraIdleListener {
            if (fencesAddActivity.isEdit) {
                //编辑的第一次不去计算距离
                if (isEditFirst) {
                    isEditFirst = false
                } else {
                    mapOkAndDistanceEdit()
                }
            } else {
                mapOkAndDistance()
            }
        }

        if (fencesAddActivity.isEdit) {
            locationSuccess(null)
        } else {
            getLastLocation()
        }
    }

    /**
     * 地图准备好计算距离
     */
    fun mapOkAndDistance() {
        if (null == mActivity) return
        val arrayOfDistance = getLatLngAndCalDistance()
        mOnActivityCallBack?.calculationDistance(arrayOfDistance)
    }

    private fun getLatLngAndCalDistance(): Array<String> {
        val fencesAddActivity = mActivity as FencesAddActivity
        // 经纬度转换为手机坐标点
//            val x = mGoogleMap!!.projection.toScreenLocation(it).x
//            val y = mGoogleMap!!.projection.toScreenLocation(it).y

        //手机坐标点转换为经纬度
        val centreLatLng = fencesAddActivity.getCentrePoint()
            .let { mGoogleMap!!.projection.fromScreenLocation(it) }
        mCenterLatLng = centreLatLng

        return if (fencesAddActivity.mFenceShapeType == ConstantInt.CircleShapeType) {
            val endLatLng = fencesAddActivity.getCircleLineEndPoint()
                .let { mGoogleMap!!.projection.fromScreenLocation(it) }
            mEndLatLng = endLatLng
            LogUtil.e("GoogleMap,setOnCameraIdleListener 监听回调")
            LogUtil.e("startLatLng=$centreLatLng,endLatLng=$endLatLng")
            val distance = Util.measureLatLonDistance(
                centreLatLng.latitude,
                centreLatLng.longitude,
                endLatLng.latitude,
                endLatLng.longitude
            )
            arrayOf(
                Utils.formatDecimal(distance, 2)
            )
        } else {
            mRectALatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_A).let {
                mGoogleMap!!.projection.fromScreenLocation(it)
            }
            mRectBLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_B).let {
                mGoogleMap!!.projection.fromScreenLocation(it)
            }
            mRectCLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_C).let {
                mGoogleMap!!.projection.fromScreenLocation(it)
            }
            mRectDLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_D).let {
                mGoogleMap!!.projection.fromScreenLocation(it)
            }
            val rectWidthDistance = Util.measureLatLonDistance(
                mRectALatLng!!.latitude,
                mRectALatLng!!.longitude,
                mRectBLatLng!!.latitude,
                mRectBLatLng!!.longitude
            )
            val rectHeightDistance = Util.measureLatLonDistance(
                mRectALatLng!!.latitude,
                mRectALatLng!!.longitude,
                mRectCLatLng!!.latitude,
                mRectCLatLng!!.longitude
            )
            //长度和高度
            arrayOf(
                Utils.formatDecimal(rectWidthDistance, 2),
                Utils.formatDecimal(rectHeightDistance, 2)
            )
        }
    }

    /**
     * 编辑围栏返回的距离
     */
    private fun mapOkAndDistanceEdit() {
        if (null == mActivity) return
        val arrayOfDistance = getLatLngAndCalDistance()

        //测试矩形围栏编辑还原
//        mGoogleMap!!.clear()
//        val bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ico_map)
//        val optionA = MarkerOptions().position(mRectALatLng!!).icon(bitmap)
//        mGoogleMap!!.addMarker(optionA)
//        val optionB = MarkerOptions().position(mRectBLatLng!!).icon(bitmap)
//        mGoogleMap!!.addMarker(optionB)
//        val optionC = MarkerOptions().position(mRectCLatLng!!).icon(bitmap)
//        mGoogleMap!!.addMarker(optionC)
//        val optionD = MarkerOptions().position(mRectDLatLng!!).icon(bitmap)
//        mGoogleMap!!.addMarker(optionD)

        mOnActivityCallBack?.calculationDistance(arrayOfDistance)
    }

    override fun locationSuccess(location: Location?) {
        LogUtil.e("$mCenterLatLng,locationSuccess locationSuccess,$location")
        if (null != location) {
            //初始化开始起点位置(中心圆)
            mCenterLatLng = LatLng(location.latitude, location.longitude)
        }
        moveCameraLocation(mCenterLatLng!!, false)

        mOnActivityCallBack?.mapCompletion()
    }

    private lateinit var mMapBoxSearchView: SearchView

    fun initMapBox(
        context: Context,
        searchResultsViewLayout: LinearLayoutCompat,
        addressEditText: AppCompatEditText
    ) {
        LogUtil.e("---------------------------initMapBox-------------------")
        mMapBoxSearchView = SearchView(context)
        //判断有没有初始化
        if (!this::mSearchResultsView.isInitialized) {
            mSearchResultsView = SearchResultsView(context)
            mSearchResultsView.apply {
                layoutParams = LinearLayoutCompat.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                )
                background = ContextCompat.getDrawable(context, R.drawable.shape20_white_bg)
                elevation = QMUIDisplayHelper.dpToPx(10).toFloat()
            }
        }

        mSearchResultsView.apply {
            //单位
//            initialize(CommonSearchViewConfiguration(DistanceUnitType.METRIC))
            isVisible = false

//            isHapticFeedbackEnabled = false

//            addSearchListener(object : SearchResultsView.SearchListener {
//                override fun onSearchResult(
//                    searchResult: SearchResult, responseInfo: ResponseInfo
//                ) {
//                    mSearchResultsView.isVisible = false
//                    LogUtil.e("Search result: $searchResult")
//                    //发起请求时的经纬度
////                    val lat = searchResult.requestOptions.options.origin!!.coordinates()[1]
////                    val lon = searchResult.requestOptions.options.origin!!.coordinates()[0]
//
//                    //搜索到的经纬度
//                    val resultLat = searchResult.coordinate!!.latitude()
//                    val resultLon = searchResult.coordinate!!.longitude()
//                    setCameraUpdateNull()
//                    moveCameraLocation(LatLng(resultLat, resultLon))
//                }
//
//                override fun onHistoryItemClicked(historyRecord: HistoryRecord) {
////                    searchView.setQuery(historyRecord.name, true)
////                    LogUtil.e("${historyRecord.name}")
//                    //历史搜索
//                    addressEditText.setText(historyRecord.name)
//                    searchAddress(addressEditText.text.toString())
//                }
//
//                override fun onPopulateQueryClicked(
//                    suggestion: SearchSuggestion, responseInfo: ResponseInfo
//                ) {
//                    mMapBoxSearchView.setQuery(suggestion.name, true)
//                    LogUtil.e("onPopulateQueryClicked")
//                }
//
//                override fun onFeedbackClicked(responseInfo: ResponseInfo) {
//                    // Not implemented
//                }
//            })
        }

        searchResultsViewLayout.apply {
            visibility = View.VISIBLE
            addView(mSearchResultsView)
        }
    }

    /**
     * 经纬度转换为屏幕坐标点
     */
    fun latLngToPotion(wherePoint: Int): Point? {
        mGoogleMap?.apply {
            when (wherePoint) {
                FencesPolygonView.POINT_A -> return projection.toScreenLocation(mRectALatLng!!)
                FencesPolygonView.POINT_B -> return projection.toScreenLocation(mRectBLatLng!!)
                FencesPolygonView.POINT_C -> return projection.toScreenLocation(mRectCLatLng!!)
                FencesPolygonView.POINT_D -> return projection.toScreenLocation(mRectDLatLng!!)
            }
        }
        return null
    }

    /**
     * 设置圆形围栏，地图缩放级别
     */
    fun setCircleMapZoom(distance: Double) {
        val zoom = getDistanceZoom(distance)
        LogUtil.e("谷歌地图zoom==$zoom")
        setGoogleMapZoom(zoom)
    }

    /**
     * 设置矩形 地图缩放级别
     */
    fun setRectMapZoom(
        context: Context,
        rectALatLng: LatLng,
        rectBLatLng: LatLng,
        rectCLatLng: LatLng,
        rectDLatLng: LatLng
    ) {
        setLatLngZoom(context, 300, rectALatLng, rectBLatLng, rectCLatLng, rectDLatLng)
    }

    /**
     * 搜索地址,地理编码
     */
    fun searchAddress(keyword: String) {
        if (TextUtils.isEmpty(keyword)) {
            return
        }
        mSearchResultsView.apply {
            isVisible = true
//            search(keyword)
        }
    }

    /**
     * 隐藏搜索检索结果页面
     */
    fun setSearchResultsViewGone() {
        mSearchResultsView.isVisible = false
    }

    fun setOnCalculationDistance(onActivityCallBack: FencesMapCommon.OnActivityCallBack) {
        mOnActivityCallBack = onActivityCallBack
    }
}