package com.grkj.iscs.view.widget

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.util.Pair
import android.view.MotionEvent
import com.grkj.iscs.R
import com.grkj.iscs.view.fragment.WorkshopFragment.CustomPoint
import com.onlylemi.mapview.library.MapView
import com.onlylemi.mapview.library.layer.MapBaseLayer
import com.onlylemi.mapview.library.utils.MapMath
import kotlin.math.cos
import kotlin.math.sin

class CustomMarkLayer @JvmOverloads constructor(
    mapView: MapView?,
    private var pointList: List<CustomPoint> = mutableListOf()
) : MapBaseLayer(mapView) {
    private var listener: MarkIsClickListener? = null
    private var radiusMark = 0f
    private var isClickMark: Boolean = false
    private var num: Int
    private lateinit var paint: Paint
    private var btnIndex: Int
    private var currentZoom = 0f
    private var currentDegree = 0f
    private lateinit var icon: Bitmap
    private lateinit var iconRepair: Bitmap
    private lateinit var iconPreMaintenance: Bitmap
    private lateinit var iconChangeShifts: Bitmap
    private lateinit var iconClean: Bitmap
    private lateinit var iconSwitchProduct: Bitmap

    init {
        num = -1
        btnIndex = -1
        initLayer()
    }

    private fun initLayer() {
        radiusMark = setValue(10.0f)
        icon = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_repair)
        iconRepair = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_repair)
        iconPreMaintenance = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_pre_maintenance)
        iconChangeShifts = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_change_shifts)
        iconClean = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_clean)
        iconSwitchProduct = BitmapFactory.decodeResource(mapView.resources, R.mipmap.map_switch_product)
        paint = Paint()
        paint.isAntiAlias = true
        paint.style = Paint.Style.FILL_AND_STROKE
    }

    override fun onTouch(event: MotionEvent) {
        if (pointList.isNotEmpty()) {
            val goal = mapView.convertMapXYToScreenXY(event.x, event.y)

            for (i in pointList.indices) {
                val list = pointList[i].ticketList
                var continueOuterLoop = false // 双循环跳出标志变量

                // 计算文字点击
                val width = paint.measureText(pointList[i].name) / currentZoom

                val left = pointList[i].pos.x - (width / 2 + radiusMark / 4.0f * 3) / currentZoom
                val top = pointList[i].pos.y - radiusMark / 4.0f * 3 / currentZoom
                val right = pointList[i].pos.x + (width / 2 + radiusMark / 4.0f * 3) / currentZoom
                val bottom = pointList[i].pos.y + radiusMark / 4.0f * 3 / currentZoom

                if (goal[0] > left && goal[0] < right && goal[1] > top && goal[1] < bottom) {
                    num = i
                    btnIndex = -1
                    isClickMark = true
                    break
                }

                // 计算图标点击
                for (j in list.indices) {
                    val ticketX = if (list.size % 2 == 0) { // 偶数个
                        if (j + 1 <= list.size / 2) {
                            pointList[i].pos.x - icon.width * (list.size / 2 - j - 0.5f) / currentZoom
                        } else {
                            pointList[i].pos.x + icon.width * (j - list.size / 2 + 0.5f) / currentZoom
                        }
                    } else {    // 奇数个
                        if (j + 1 <= list.size / 2) {
                            pointList[i].pos.x - icon.width * (list.size / 2 - j) / currentZoom
                        } else {
                            pointList[i].pos.x + icon.width * (j - list.size / 2) / currentZoom
                        }
                    }
                    val rotatedPoint = rotatePoint(
                        ticketX,
                        pointList[i].pos.y - icon.height / currentZoom,
                        pointList[i].pos.x,
                        pointList[i].pos.y,
                        currentDegree
                    )

                    val distance = MapMath.getDistanceBetweenTwoPoints(
                        goal[0], goal[1],
                        rotatedPoint.first,
                        rotatedPoint.second
                    )

                    if (distance <= icon.width / 2 / currentZoom) {
                        num = i
                        btnIndex = j
                        isClickMark = true
                        continueOuterLoop = true
                        break
                    }
                }

                // 跳出外层循环
                if (continueOuterLoop) break

                if (i == pointList.size - 1) {
                    isClickMark = false
                }
            }

            if (listener != null && isClickMark) {
                listener!!.markIsClick(num, btnIndex)
                mapView.refresh()
            }
        }
    }

    override fun draw(
        canvas: Canvas,
        currentMatrix: Matrix,
        currentZoom: Float,
        currentRotateDegrees: Float
    ) {
        this.currentZoom = currentZoom
        currentDegree = 360 - currentRotateDegrees
        if (isVisible) {
            canvas.save()
            if (pointList.isNotEmpty()) {
                pointList.forEach { point ->
                    val mark = point.pos
                    val goal = floatArrayOf(mark.x, mark.y)
                    currentMatrix.mapPoints(goal)

                    // 文字背景
                    val width = paint.measureText(point.name)
                    paint.color = Color.parseColor("#70b26f")
                    paint.style = Paint.Style.FILL
                    paint.strokeWidth = 1.0f
                    // 圆角矩形
                    canvas.drawRoundRect(
                        goal[0] - width / 2 - radiusMark / 4.0f * 3,
                        goal[1] - radiusMark / 4.0f * 3,
                        goal[0] + width / 2 + radiusMark / 4.0f * 3,
                        goal[1] + radiusMark / 4.0f * 3,
                        10f,
                        10f,
                        paint
                    )

                    paint.color = Color.parseColor("#FFFFFF")
                    paint.textSize = radiusMark
//                    if (mapView.currentZoom.toDouble() > 0.8) {
                    // 一直显示文字
                        canvas.drawText(
                            point.name,
                            goal[0] - width / 2,
                            goal[1] + radiusMark / 3.0f,
                            paint
                        )
//                    }

                    val list = point.ticketList
                    if (list.isNotEmpty()) {
                        for (j in list.indices) {
                            canvas.drawBitmap(
                                when(list[j].ticketType) {
                                    "0" -> iconRepair
                                    "1" -> iconPreMaintenance
                                    "2" -> iconChangeShifts
                                    "3" -> iconClean
                                    "4" -> iconSwitchProduct
                                    else -> iconRepair
                                },
                                // 偶数个
                                if (list.size % 2 == 0) {
                                    if (j + 1 <= list.size / 2) {
                                        goal[0] - icon.width * (list.size / 2 - j)
                                    } else {
                                        goal[0] + icon.width * (j - list.size / 2)
                                    }
                                } else {    // 奇数个
                                    if (j + 1 <= list.size / 2) {
                                        goal[0] - icon.width * (list.size / 2 - j + 0.5f)
                                    } else {
                                        goal[0] + icon.width * (j - list.size / 2 - 0.5f)
                                    }
                                },
                                goal[1] - icon.height / 2 * 3,
                                paint
                            )
                        }
                    }
                    // 定位点，仅调试用，不要显示
//                    canvas.drawCircle(goal[0], goal[1], 2f, paint)
                }
            }

            canvas.restore()
        }
    }

    private fun rotatePoint(
        oriX: Float, oriY: Float, desX: Float, desY: Float, rotateDegrees: Float
    ): Pair<Float, Float> {
        // 将度数转换为弧度
        val theta = Math.toRadians(rotateDegrees.toDouble())

        // 计算旋转后的坐标
        val newX = (oriX - desX) * cos(theta) - (oriY - desY) * sin(theta) + desX
        val newY = (oriX - desX) * sin(theta) + ((oriY - desY) * cos(theta)) + desY

        return Pair(newX.toFloat(), newY.toFloat())
    }

    fun setMarkIsClickListener(listener: MarkIsClickListener?) {
        this.listener = listener
    }

    interface MarkIsClickListener {
        fun markIsClick(index: Int, btnIndex: Int)
    }
}
