package com.abbidot.tracker.ui.common.map

import android.content.Context
import android.graphics.Point
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.vm.ScreenshotsViewModel
import com.abbidot.tracker.deprecated.ui.fragment.map.baidumap.FencesAddBaiduMapFragment
import com.abbidot.tracker.deprecated.ui.fragment.map.googlemap.FencesAddGoogleMapFragment
import com.abbidot.tracker.util.LonAndLatUtil
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.widget.FencesPolygonView
import com.google.android.gms.maps.model.LatLng
import kotlin.math.pow


/**
 *Created  by .yzq on 2022/7/5/005.
 * @link
 * @description:
 */
class FencesMapCommon {

    private var mFencesAddGoogleMapFragment: FencesAddGoogleMapFragment? = null
    private var mFencesAddBaiduMapFragment: FencesAddBaiduMapFragment? = null

    fun getMapFragment(
        context: Context,
        recyclerView: RecyclerView,
        searchResultsViewLayout: LinearLayoutCompat,
        addressEditText: AppCompatEditText,
        onActivityCallBack: OnActivityCallBack
    ): Fragment {
        return if (AppUtils.isChina(AppUtils.SWITCH_MAP_TYPE)) {
            mFencesAddBaiduMapFragment = FencesAddBaiduMapFragment.newInstance(context)
            mFencesAddBaiduMapFragment!!.setOnCalculationDistance(onActivityCallBack)
            mFencesAddBaiduMapFragment!!.initRecyclerView(context, recyclerView)
            mFencesAddBaiduMapFragment!!
        } else {
            mFencesAddGoogleMapFragment = FencesAddGoogleMapFragment.newInstance(context)
            mFencesAddGoogleMapFragment!!.setOnCalculationDistance(onActivityCallBack)
            mFencesAddGoogleMapFragment!!.initMapBox(
                context, searchResultsViewLayout, addressEditText
            )
            mFencesAddGoogleMapFragment!!
        }
    }

    /**
     * 根据地图显示级别,计算比例尺的一像素对应几米
     */
    fun getCircleRadiusPx(circleRadius: Double): Double {
        var px = 0.0
        if (null != mFencesAddGoogleMapFragment) {
            val zoom = mFencesAddGoogleMapFragment!!.getGoogleMapZoom()
            //一像素对应几米
            val pxDis = 2.0.pow((15.5 - zoom))
            //计算现在半径有多少像素
            px = circleRadius / pxDis
        } else if (null != mFencesAddBaiduMapFragment) {
            val zoom = mFencesAddBaiduMapFragment!!.getBaiduMapZoom()
            //一像素对应几米
            val pxDis = 2.0.pow((18 - zoom).toDouble())
            //计算现在半径有多少像素
            px = circleRadius / pxDis
        }
        return px
    }

    fun setCenterLatLng(latitude: Double, longitude: Double, radius: Double = 0.0) {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.mCenterLatLng = LatLng(latitude, longitude)
            //设置地图缩放级别，让圆形围栏显示完整
            if (radius > 0.0) mFencesAddGoogleMapFragment?.setCircleMapZoom(radius)
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.apply {
                //百度地图使用GCJ02坐标
                mCenterLatLng = getBaiduMapLatLng(latitude, longitude)
                LogUtil.e("编辑转换中心坐标$mCenterLatLng,gps的$latitude，$longitude")
                //设置地图缩放级别，让圆形围栏显示完整
                if (radius > 0.0) mFencesAddBaiduMapFragment?.setCircleMapZoom(radius)
            }
        }
    }

    /**
     * 获取开始点（中间点）的经纬度
     */
    fun getCenterLatLng(): DoubleArray {
        var dd = DoubleArray(2)
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.mCenterLatLng?.let {
                dd[0] = it.latitude
                dd[1] = it.longitude
            }
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.mCenterLatLng?.let {
                //转换原始gps坐标
                dd = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
            }
        }
        return dd
    }


    fun setRectABCDLatLng(
        context: Context,
        longitudeA: Double,
        latitudeA: Double,
        longitudeB: Double,
        latitudeB: Double,
        longitudeC: Double,
        latitudeC: Double,
        longitudeD: Double,
        latitudeD: Double
    ) {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment?.apply {
                mRectALatLng = LatLng(latitudeA, longitudeA)
                mRectBLatLng = LatLng(latitudeB, longitudeB)
                mRectCLatLng = LatLng(latitudeC, longitudeC)
                mRectDLatLng = LatLng(latitudeD, longitudeD)
                //设置地图缩放级别，让矩形围栏显示完整
                mFencesAddGoogleMapFragment?.setRectMapZoom(
                    context, mRectALatLng!!, mRectBLatLng!!, mRectCLatLng!!, mRectDLatLng!!
                )
            }
        } else if (null != mFencesAddBaiduMapFragment) {
            //百度地图使用GCJ02坐标
            mFencesAddBaiduMapFragment?.apply {
                mRectALatLng = getBaiduMapLatLng(latitudeA, longitudeA)
                mRectBLatLng = getBaiduMapLatLng(latitudeB, longitudeB)
                mRectCLatLng = getBaiduMapLatLng(latitudeC, longitudeC)
                mRectDLatLng = getBaiduMapLatLng(latitudeD, longitudeD)
                LogUtil.e("没有加密的4个点经纬度$latitudeA,$longitudeA,\n$latitudeB.$longitudeB,\n$latitudeC,$longitudeC,\n$latitudeD,$longitudeD")
                LogUtil.e("编辑的4个点经纬度$mRectALatLng,\n$mRectBLatLng,\n$mRectCLatLng,\n$mRectDLatLng,\n$mCenterLatLng")
                //设置地图缩放级别，让矩形围栏显示完整
                mFencesAddBaiduMapFragment?.setRectMapZoom(
                    mRectALatLng!!, mRectBLatLng!!, mRectCLatLng!!, mRectDLatLng!!
                )
//                mFencesAddBaiduMapFragment?.setRectMapZoom(com.baidu.mapapi.model.LatLng(latitudeA, longitudeA), com.baidu.mapapi.model.LatLng(latitudeB, longitudeB),
//                    com.baidu.mapapi.model.LatLng(latitudeC, longitudeC), com.baidu.mapapi.model.LatLng(latitudeD, longitudeD))
            }
        }
    }

    /**
     * 经纬度转换为屏幕坐标点
     */
    fun latLngToPotion(wherePoint: Int): Point? {
        if (null != mFencesAddGoogleMapFragment) {
            return mFencesAddGoogleMapFragment!!.latLngToPotion(wherePoint)
        } else if (null != mFencesAddBaiduMapFragment) {
            return mFencesAddBaiduMapFragment!!.latLngToPotion(wherePoint)
        }
        return null
    }

    /**
     * 获取矩形ABCD的经纬度
     */
    fun getRectABCDLatLng(wherePoint: Int): DoubleArray {
        var dd = DoubleArray(2)
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment?.apply {
                when (wherePoint) {
                    FencesPolygonView.POINT_A -> mRectALatLng?.let {
                        dd[0] = it.latitude
                        dd[1] = it.longitude
                    }

                    FencesPolygonView.POINT_B -> mRectBLatLng?.let {
                        dd[0] = it.latitude
                        dd[1] = it.longitude
                    }

                    FencesPolygonView.POINT_C -> mRectCLatLng?.let {
                        dd[0] = it.latitude
                        dd[1] = it.longitude
                    }

                    FencesPolygonView.POINT_D -> mRectDLatLng?.let {
                        dd[0] = it.latitude
                        dd[1] = it.longitude
                    }
                }

            }
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment?.apply {
                when (wherePoint) {
                    FencesPolygonView.POINT_A -> mRectALatLng?.let {
                        //转换原始gps坐标
                        dd = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
                    }

                    FencesPolygonView.POINT_B -> mRectBLatLng?.let {
                        //转换原始gps坐标
                        dd = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
                    }

                    FencesPolygonView.POINT_C -> mRectCLatLng?.let {
                        //转换原始gps坐标
                        dd = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
                    }

                    FencesPolygonView.POINT_D -> mRectDLatLng?.let {
                        //转换原始gps坐标
                        dd = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
                    }
                }

            }
        }
        return dd
    }

    /**
     * 刷新显示距离，点击围栏样式刷新
     */
    fun refreshDistance() {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.mapOkAndDistance()
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.mapOkAndDistance()
        }
    }

    /**
     * 隐藏搜索检索结果页面
     */
    fun setSearchResultsViewGone() {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.setSearchResultsViewGone()
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.setSearchResultsViewGone()
        }
    }

    /**
     * 搜索地址
     */
    fun searchAddress(keyword: String) {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.searchAddress(keyword)
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.searchAddress(keyword)
        }
    }

    /**
     * 经纬度转换地址
     */
    fun getLatLonAddress(geoCoderViewModel: GeoCoderViewModel) {
        if (null != mFencesAddGoogleMapFragment) {
            mFencesAddGoogleMapFragment!!.mCenterLatLng?.let {
                geoCoderViewModel.getLatLonAddress(it.latitude, it.longitude)
            }
        } else if (null != mFencesAddBaiduMapFragment) {
            mFencesAddBaiduMapFragment!!.mCenterLatLng?.let {
                val convertLonLat = LonAndLatUtil.convertFromGCJ02ToWGS84(it.latitude, it.longitude)
                geoCoderViewModel.getLatLonAddress(convertLonLat[0], convertLonLat[1])
            }
        }
    }

    /**
     * 截屏并上传图片
     */
    fun snapshotImage(
        activity: BaseActivity<*>, screenshotsViewModel: ScreenshotsViewModel, snapshotView: View
    ) {
        if (null != mFencesAddGoogleMapFragment) {
            if (null == mFencesAddGoogleMapFragment!!.mGoogleMap) {
                activity.showToast(com.abbidot.tracker.R.string.txt_load_map)
                return
            }
            screenshotsViewModel.fencesGoogleMapSnapshotImage(
                activity,
                mFencesAddGoogleMapFragment!!.mGoogleMap!!,
                snapshotView,
                fileName = "add_fence_${System.currentTimeMillis() / 1000}.png"
            )
        } else if (null != mFencesAddBaiduMapFragment) {
            if (null == mFencesAddBaiduMapFragment!!.mBaiduMap) {
                activity.showToast(com.abbidot.tracker.R.string.txt_load_map)
                return
            }
            screenshotsViewModel.fencesBaiduMapSnapshotImage(
                activity,
                mFencesAddBaiduMapFragment!!.mBaiduMap!!,
                snapshotView,
                fileName = "add_fence_${System.currentTimeMillis() / 1000}.png"
            )
        }
    }

    interface OnActivityCallBack {
        fun calculationDistance(distances: Array<String>)
        fun mapCompletion()
    }
}