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

import android.content.Context
import android.graphics.Point
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.BaiduMapPoiSearchResultAdapter
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.baidumap.BaseBaiduMapFragment
import com.abbidot.tracker.util.LonAndLatUtil.Companion.getMaxLatOrLon
import com.abbidot.tracker.util.LonAndLatUtil.Companion.getMinLatOrLon
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.widget.FencesPolygonView
import com.baidu.location.BDLocation
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.GeoCodeResult
import com.baidu.mapapi.search.geocode.GeoCoder
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener
import com.baidu.mapapi.search.poi.PoiCitySearchOption
import com.baidu.mapapi.search.poi.PoiDetailResult
import com.baidu.mapapi.search.poi.PoiDetailSearchResult
import com.baidu.mapapi.search.poi.PoiIndoorResult
import com.baidu.mapapi.search.poi.PoiResult
import com.baidu.mapapi.search.poi.PoiSearch
import com.hjq.toast.Toaster


/**
 *Created  by .yzq on 2022/7/4/004.
 * @link
 * @description:
 */
class FencesAddBaiduMapFragment : BaseBaiduMapFragment() {

    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 var mCity = ""
    private lateinit var mPoiSearchResultAdapter: BaiduMapPoiSearchResultAdapter
    private lateinit var mRecyclerView: RecyclerView

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

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

    override fun onMapLoadOk(baiduMap: BaiduMap) {
        val fencesAddActivity = mActivity as FencesAddActivity
        //设置地图渲染完成回调,拖动动图回调
        mBaiduMap?.setOnMapRenderCallbadk {
            if (fencesAddActivity.isEdit) {
                //编辑的第一次不去计算距离
                if (isEditFirst) {
                    isEditFirst = false
                } else {
                    mapOkAndDistanceEdit()
                }
            } else {
                mapOkAndDistance()
            }
        }

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

        //测试矩形围栏使用的代码
//        if (null != mRectALatLng) {
//            val points = mutableListOf<LatLng>()
//            points.add(LatLng(mRectALatLng!!.latitude, mRectALatLng!!.longitude))
//            points.add(LatLng(mRectBLatLng!!.latitude, mRectBLatLng!!.longitude))
//            points.add(LatLng(mRectDLatLng!!.latitude, mRectDLatLng!!.longitude))
//            points.add(LatLng(mRectCLatLng!!.latitude, mRectCLatLng!!.longitude))
//            //构造PolygonOptions
//            val polygonOptions = PolygonOptions().points(points)
//                //是否显示虚线
//                .dottedStroke(true)
//                //填充颜色
//                .fillColor(ContextCompat.getColor(requireContext(), R.color.map_circle_color1))
//                //边框宽和边框颜色
//                .stroke(
//                    Stroke(
//                        QMUIDisplayHelper.dpToPx(2),
//                        ContextCompat.getColor(requireContext(), R.color.btn_yellow_color)
//                    )
//                )
//            mBaiduMap!!.addOverlay(polygonOptions)
//        }
    }

    /**
     * 地图准备好计算距离
     */
    fun mapOkAndDistance() {
        if (null == mActivity) return

        val arrayOfDistance = getLatLngAndCalDis()
        mOnActivityCallBack?.calculationDistance(arrayOfDistance)

        //构建Marker图标
        mRectALatLng?.apply {
//            mBaiduMap!!.clear()
//            val bitmap = BitmapDescriptorFactory.fromResource(R.drawable.pic_map_location)
//            val optionA: OverlayOptions = MarkerOptions().position(mRectALatLng).icon(bitmap)
//            mBaiduMap!!.addOverlay(optionA)
//            val optionB: OverlayOptions = MarkerOptions().position(mRectBLatLng).icon(bitmap)
//            mBaiduMap!!.addOverlay(optionB)
//            val optionC: OverlayOptions = MarkerOptions().position(mRectCLatLng).icon(bitmap)
//            mBaiduMap!!.addOverlay(optionC)
//            val optionD: OverlayOptions = MarkerOptions().position(mRectDLatLng).icon(bitmap)
//            mBaiduMap!!.addOverlay(optionD)
//
            LogUtil.e("新建的4个点经纬度$mRectALatLng,\n$mRectBLatLng,\n$mRectCLatLng,\n$mRectDLatLng,\n$mCenterLatLng")
        }
    }

    /**
     * 获取屏幕上的经纬度并计算距离
     */
    private fun getLatLngAndCalDis(): Array<String> {
        val fencesAddActivity = mActivity as FencesAddActivity
        //手机坐标点转换为经纬度
        val centreLatLng =
            fencesAddActivity.getCentrePoint().let { mBaiduMap!!.projection.fromScreenLocation(it) }
        mCenterLatLng = centreLatLng

        //        val sss = mBaiduMap!!.projection.toScreenLocation(mCenterLatLng)
//        LogUtil.e("errerererererer$sss")

        return if (fencesAddActivity.mFenceShapeType == ConstantInt.CircleShapeType) {
            val endLatLng = fencesAddActivity.getCircleLineEndPoint()
                .let { mBaiduMap!!.projection.fromScreenLocation(it) }
            mEndLatLng = endLatLng
            LogUtil.e("BaiduMap,mapOkAndDistance,setOnMapRenderCallbadk ")
            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 {
                mBaiduMap!!.projection.fromScreenLocation(it)
            }
            mRectBLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_B).let {
                mBaiduMap!!.projection.fromScreenLocation(it)
            }
            mRectCLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_C).let {
                mBaiduMap!!.projection.fromScreenLocation(it)
            }
            mRectDLatLng = fencesAddActivity.getRectABCDPoint(FencesPolygonView.POINT_D).let {
                mBaiduMap!!.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 = getLatLngAndCalDis()

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

        mOnActivityCallBack?.calculationDistance(arrayOfDistance)
    }

    fun initRecyclerView(context: Context, recyclerView: RecyclerView) {
        mPoiSearchResultAdapter = BaiduMapPoiSearchResultAdapter(context, null)
        mPoiSearchResultAdapter.setOnItemClickListener(object :
            BaseRecyclerAdapter.OnItemClickListener {
            override fun onItemClick(itemView: View?, pos: Int) {
                val item = mPoiSearchResultAdapter.getItem(pos)
                setSearchResultsViewGone()
                moveCameraLocation(
                    item.location.latitude, item.location.longitude, needConvertGCJ02 = false
                )
            }
        })
        mRecyclerView = recyclerView
        mRecyclerView.addItemDecoration(DividerItemDecoration(context, LinearLayout.VERTICAL))
        ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
            context, mRecyclerView, mPoiSearchResultAdapter
        )
    }

    /**
     * 经纬度转换为屏幕坐标点
     */
    fun latLngToPotion(wherePoint: Int): Point? {
        mBaiduMap?.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")
        setBaiduMapZoom(zoom)
    }

    /**
     * 设置矩形围栏，地图缩放级别
     */
    fun setRectMapZoom(
        rectALatLng: LatLng, rectBLatLng: LatLng, rectCLatLng: LatLng, rectDLatLng: LatLng
    ) {
        val maxLat = getMaxLatOrLon(
            rectALatLng.latitude, rectBLatLng.latitude, rectCLatLng.latitude, rectDLatLng.latitude
        )
        val maxLon = getMaxLatOrLon(
            rectALatLng.longitude,
            rectBLatLng.longitude,
            rectCLatLng.longitude,
            rectDLatLng.longitude
        )
        val minLat = getMinLatOrLon(
            rectALatLng.latitude, rectBLatLng.latitude, rectCLatLng.latitude, rectDLatLng.latitude
        )
        val minLon = getMinLatOrLon(
            rectALatLng.longitude,
            rectBLatLng.longitude,
            rectCLatLng.longitude,
            rectDLatLng.longitude
        )
        val zoom = getDistanceZoom(LatLng(minLat, minLon), LatLng(maxLat, maxLon))
        LogUtil.e("百度地图zoom==$zoom")
        setBaiduMapZoom(zoom)
    }

    /**
     * 隐藏搜索检索结果页面
     */
    fun setSearchResultsViewGone() {
        mRecyclerView.visibility = View.GONE
    }

    /**
     * 搜索某个地点
     * 百度地图检索需要城市，把当前定位的经纬度转换城市
     */
    fun searchAddress(keyword: String) {
        if (TextUtils.isEmpty(keyword)) {
            setSearchResultsViewGone()
            return
        }
        if (TextUtils.isEmpty(mCity)) {
            showToast(R.string.txt_load_map)
            return
        }
        showLoading(true)
        val poiSearch = PoiSearch.newInstance()
        poiSearch.setOnGetPoiSearchResultListener(object : OnGetPoiSearchResultListener {
            override fun onGetPoiResult(poiResult: PoiResult?) {
                showLoading(false)
                if (poiResult == null || poiResult.error === SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    Toaster.show("未找到结果")
                    return
                }
                try {
                    val poiInfo = poiResult.allPoi
                    if (poiInfo.size > 0) {
                        for (p in poiInfo) {
                            LogUtil.d(p.toString())
                        }
                        mRecyclerView.visibility = View.VISIBLE
                        mPoiSearchResultAdapter.setData(poiInfo, true)
                    }
                } catch (e: Exception) {
                    mRecyclerView.visibility = View.GONE
                }
            }

            override fun onGetPoiDetailResult(p0: PoiDetailResult?) {
            }

            override fun onGetPoiDetailResult(p0: PoiDetailSearchResult?) {
            }

            override fun onGetPoiIndoorResult(p0: PoiIndoorResult?) {
            }
        })
        poiSearch.searchInCity(
            PoiCitySearchOption().cityLimit(false).city(mCity).keyword(keyword).pageCapacity(15)
                .pageNum(0)
        )
        poiSearch.destroy()
    }

    /**
     * 百度地图检索需要城市，把当前定位的经纬度转换城市
     */
    private fun getCity() {
        val coder = GeoCoder.newInstance()
        coder.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {
            override fun onGetGeoCodeResult(p0: GeoCodeResult?) {

            }

            override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {
                if (null == result || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                    return
                } else {
                    mCity = try {
                        result.addressDetail.city
                    } catch (e: Exception) {
                        "北京"
                    }
                }
            }
        })
        coder.reverseGeoCode(
            ReverseGeoCodeOption().location(mCenterLatLng) // 设置是否返回新数据 默认值0不返回，1返回
                .newVersion(1) // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                .radius(500)
        )
        coder.destroy()
    }

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

        moveCameraLocation(
            mCenterLatLng!!.latitude, mCenterLatLng!!.longitude, needConvertGCJ02 = false
        )

        mOnActivityCallBack?.mapCompletion()
        getCity()
    }

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