package com.cr.map

import android.content.Context
import android.view.MotionEvent
import com.cr.dialog.DialogNormal
import com.esri.arcgisruntime.ArcGISRuntimeException
import com.esri.arcgisruntime.data.Feature
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReference
import com.esri.arcgisruntime.layers.Layer
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import java.text.DecimalFormat

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/4/18 08:44
 * 描述：地图Touch
 */
class MapTouch constructor(context: Context, mapView: MapView) :
    DefaultMapViewOnTouchListener(context, mapView) {

    /**
     * Touch回调
     */
    interface TouchListener {
        // todo: 2023/4/18 选择
        fun onSelect(feature: Feature?, layer: Layer)

        // todo: 2023/4/19 添加标志
        fun onMarkAppend(mapPoint:Point)

        // todo: 2023/6/7 查询位置返回
        fun onQueryLocation(location:Point,longitude:String,latitude:String)

        // todo: 2023/6/12 添加案件点回调
        fun onAppendWaypoint(location:Point,longitude: String,latitude: String)

        // todo: 2023/6/14 删除案件点
        fun onRemoveWaypoint(screenPoint: android.graphics.Point)

        // todo: 2023/6/14 移动案件点
        fun onMoveWaypointBySelect(location: Point)

        // todo: 2023/6/15 案件上传选择
        fun onCaseUploadBySelect(screenPoint:android.graphics.Point)
    }


    // define: 2023/4/18 定义变量
    private var context: Context? = null
    private var mapView: MapView? = null

    private var queryLayer: Layer? = null  // define: 2023/4/18 查询的图层
    private var action: MapAction? = null

    // todo: 2023/4/18 监听
    private var listener: TouchListener? = null

    // todo: 2023/4/13 静态
    companion object {
        // define: 2023/4/13 WGS84坐标系框架
        val wgs84SpatialReference: SpatialReference = SpatialReference.create(4326)
    }

    /**
     * 初始化
     */
    init {
        this.context = context
        this.mapView = mapView
    }


    // todo: 2023/4/18 重写旋转事件
    override fun onRotate(event: MotionEvent?, rotationAngle: Double): Boolean {
        return false
    }

    // todo: 2023/8/4 重写点击事件
    override fun onSingleTapUp(e: MotionEvent): Boolean {
        when (action) {
            // todo: 2023/4/19 选择涂鸦
            MapAction.MapTapSelectDoodle,
            MapAction.MapTapSelectMark -> {
                identifyLayer(e!!.x.toInt(), e.y.toInt())
            }
            // todo: 2023/4/19 添加标志
            MapAction.MapTapAppendMark -> {
                var mapPoint =
                    mapView?.screenToLocation(android.graphics.Point(e!!.x.toInt(), e.y.toInt()))
                if (listener != null) listener?.onMarkAppend(mapPoint!!)
            }
            // todo: 2023/6/7 查询地理位置
            MapAction.MapTapGetLocation -> {
                var mapPoint =
                    mapView?.screenToLocation(android.graphics.Point(e!!.x.toInt(), e.y.toInt()))
                var queryPoint =
                    GeometryEngine.project(mapPoint, SpatialReference.create(4326)) as Point
                var format: DecimalFormat = DecimalFormat("#.######")
                if (listener != null) listener?.onQueryLocation(
                    mapPoint!!,
                    format.format(queryPoint.x),
                    format.format(queryPoint.y)
                )
            }
            // todo: 2023/6/12 添加案件点
            MapAction.MapTapAddWaypoint -> {
                var mapPoint =
                    mapView?.screenToLocation(android.graphics.Point(e!!.x.toInt(), e.y.toInt()))
                var queryPoint =
                    GeometryEngine.project(mapPoint, SpatialReference.create(4326)) as Point
                var format: DecimalFormat = DecimalFormat("#.######")
                if (listener != null) listener?.onAppendWaypoint(
                    mapPoint!!,
                    format.format(queryPoint.x),
                    format.format(queryPoint.y)
                )
                this.action = MapAction.MapTapNon
            }
            // todo: 2023/6/14 删除案件点
            MapAction.MapTapDeleteWaypoint -> {
                var screenPoint = android.graphics.Point(e!!.x.toInt(), e.y.toInt())
                if (listener != null) listener?.onRemoveWaypoint(screenPoint!!)
                this.action = MapAction.MapTapNon
            }
            // todo: 2023/6/14 移动案件点
            MapAction.MapTapStartMoveWaypoing -> {
                var mapPoint =
                    mapView?.screenToLocation(android.graphics.Point(e!!.x.toInt(), e.y.toInt()))
                if (listener != null) listener?.onMoveWaypointBySelect(mapPoint!!)
            }
            // todo: 2023/6/15 案件分享及上传选择
            MapAction.MapTapCaseWxAndUpload -> {
                var screenPoint = android.graphics.Point(e!!.x.toInt(), e.y.toInt())
                var mapPoint = mapView?.screenToLocation(screenPoint)
                if (listener != null) listener?.onCaseUploadBySelect(screenPoint)
            }
        }
        return true
    }

    // todo: 2023/4/18 内部函数
    private fun identifyLayer(sx: Int, sy: Int) {
        var queryPoint = android.graphics.Point(sx, sy)
        var iAsync = mapView?.identifyLayerAsync(queryLayer, queryPoint, 5.0, false)
        iAsync?.addDoneListener(Runnable {
            var feature:Feature ? = null
            try {
                var result = iAsync.get()
                if (result.elements.size >= 1) {
                    feature = result.elements[0] as Feature
                } else {
                    showWarning("未查询到任何数据！")
                }
            } catch (e: java.lang.IllegalArgumentException) {
                showError("查询错误！")
            } catch (e: ArcGISRuntimeException) {
                showError("查询错误！")
            }finally {
                if (listener != null) listener?.onSelect(feature,queryLayer!!)
            }
        })
    }

    /**
     * 显示错误消息
     * @param error String 错误消息
     */
    private fun showError(error: String) {
        DialogNormal(context!!, "错误", error).show()
    }

    /**
     * 显示警告信息
     * @param warning String 警告信息
     */
    private fun showWarning(warning: String) {
        DialogNormal(context!!, "警告", warning).show()
    }

    /**
     * 设置查询图层
     * @param layer Layer 查询图层
     */
    fun setQueryLayer(layer: Layer) {
        this.queryLayer = layer
    }

    /**
     * 设置查询图层 用于点击查询
     * @param layer Layer 图层
     * @param action MapAction 动作
     */
    fun setQueryLayer(layer: Layer?, action: MapAction?) {
        this.queryLayer = layer
        this.action = action
    }

    /**
     * 设置动作
     * @param action MapAction 动作
     */
    fun setAction(action:MapAction){
        this.action = action
    }

    /**
     * 获取当前地图操作动作
     * @return MapAction? 地图操作动作
     */
    fun getAction():MapAction?{
        return this.action
    }

    /**
     * 设置监听
     * @param listener TouchListener 监听
     */
    fun setListener(listener: TouchListener) {
        this.listener = listener
    }
}