package com.abbidot.tracker.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.Point
import android.graphics.RectF
import android.text.TextUtils
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.util.ImageUtil
import com.abbidot.tracker.util.ViewUtil
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import kotlin.math.abs

/**
 *Created  by .yzq on 2022/1/22/022.
 * @link
 * @description:添加围栏圆形，只针对围栏
 */
class FencesCircleView : View {

    private var mWidth = 0
    private var mHeight = 0

    private lateinit var mPaint: Paint
    private lateinit var mRectF: RectF

    private var mDashedColor = 0
    private var mFillBgColor = 0

    //最外面的圆半径
    private var mMaxCircleRadius = 0f

    //限制圆的半径
    var mLimitRadius = 0f

    //中心坐标点
    private var mCentreX = 0f
    private var mCentreY = 0f

    //内圆半径
    private lateinit var mInsideCirclePaint: Paint

    //定位图标
    private var mLocationBitmap: Bitmap? = null
    private var mZoomBitmap: Bitmap? = null

    //线末尾坐标点
    private var mLineEndX = 0f
    private var mLineEndY = 0f

    //是否显示距离文字
    private var isShowDistance = true

    //距离显示
    private var mDistanceText = ""
    private lateinit var mTextPaint: Paint
    private var isScale = false
    private var isDrag = false
    private var mOldX = 0f
    private var mOldY = 0f

    //是否需要测量，防止百度地图使用会执行onMeasure/地图页面上下滑动重新布局执行onMeasure
    private var isNeedMeasure = true

    private var mScaleClickListener: OnCircleViewScaleClickListener? = null

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        initAttrs(context, attrs)

        //禁用硬件加速,防止返回到界面多次执行onDraw
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        //圆的默认大小
//        mMaxCircleRadius = QMUIDisplayHelper.dpToPx(68).toFloat()
        mPaint = Paint()
        LogUtil.e("${javaClass.canonicalName}------------------->>>init")
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = QMUIDisplayHelper.dpToPx(1).toFloat()
        //虚线长度
        val dashPathWidth = QMUIDisplayHelper.dpToPx(6).toFloat()
        mPaint.pathEffect = DashPathEffect(floatArrayOf(dashPathWidth, dashPathWidth), 0f)
        mPaint.color = mDashedColor

        mTextPaint = Paint()
        val tf =
            ViewUtil.instance.setTypeface(context, context.getString(R.string.number_din_cond_font))
        mTextPaint.typeface = tf
        mTextPaint.textSize = QMUIDisplayHelper.sp2px(context, 14).toFloat()
        mTextPaint.color = ContextCompat.getColor(context, R.color.black)

        mInsideCirclePaint = Paint()
        mInsideCirclePaint.color = mFillBgColor

        mRectF = RectF()
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        if (null == attrs) {
            mDashedColor = ContextCompat.getColor(context, R.color.tab_select)
            mFillBgColor = ContextCompat.getColor(context, R.color.black20)
            mLocationBitmap =
                ImageUtil.getBitmapFromDrawableAndSvg(context, R.drawable.icon_fences_zone_gps_svg)
            mZoomBitmap = ImageUtil.getBitmapFromDrawableAndSvg(
                context, R.drawable.icon_fence_circle_scale_svg
            )
            return
        }
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FencesCircleView)
        mDashedColor = typedArray.getColor(
            R.styleable.FencesCircleView_fences_circle_dashed_color,
            ContextCompat.getColor(context, R.color.tab_select)
        )
        mFillBgColor = typedArray.getColor(
            R.styleable.FencesCircleView_fences_circle_fill_bg_color,
            ContextCompat.getColor(context, R.color.black20)
        )
        mLocationBitmap = ImageUtil.getBitmapFromDrawableAndSvg(
            context, typedArray.getResourceId(
                R.styleable.FencesCircleView_fences_circle_location_drawable,
                R.drawable.icon_fences_zone_gps_svg
            )
        )
        mZoomBitmap = ImageUtil.getBitmapFromDrawableAndSvg(
            context, typedArray.getResourceId(
                R.styleable.FencesCircleView_fences_circle_zoom_drawable,
                R.drawable.icon_fence_circle_scale_svg
            )
        )
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mWidth = measuredWidth
        mHeight = measuredHeight
        LogUtil.e("${javaClass.canonicalName}:onMeasure---mWidth=$mWidth,mHeight=$mHeight")
        if (isNeedMeasure) {
            mCentreX = mWidth / 2f
            mCentreY = mHeight / 2f
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        LogUtil.e("onAttachedToWindow,${javaClass.canonicalName}视图显示")
    }

    override fun onDraw(canvas: Canvas) {
        LogUtil.d("${javaClass.canonicalName}------>onDraw")
        super.onDraw(canvas)
        drawCircle(canvas)
    }

    private fun drawCircle(canvas: Canvas) {
        mLineEndX = mCentreX + mMaxCircleRadius
        mLineEndY = mCentreY
        canvas.drawCircle(mCentreX, mCentreY, mMaxCircleRadius, mPaint)
        canvas.drawCircle(
            mCentreX, mCentreY, mMaxCircleRadius - mPaint.strokeWidth / 2f, mInsideCirclePaint
        )
        mRectF.set(
            mCentreX - mMaxCircleRadius,
            mCentreY - mMaxCircleRadius,
            mLineEndX,
            mCentreY + mMaxCircleRadius
        )

        val imageHalfWidth = mLocationBitmap!!.width / 2f
        val imageHalfHeight = mLocationBitmap!!.height / 2f
        val left = mCentreX - imageHalfWidth
        val top = mCentreY - imageHalfHeight
        canvas.drawBitmap(mLocationBitmap!!, left, top, null)

        if (isShowDistance) {
            if (!TextUtils.isEmpty(mDistanceText)) {

//                canvas.drawLine(mCentreX + imageHalfWidth, mCentreY, mLineEndX, mLineEndY, mPaint)

                //文字宽度
                val textWidth = mTextPaint.measureText(mDistanceText)
                val fontMetrics = mTextPaint.fontMetrics
                //文字高度
                val textHeight = fontMetrics.bottom - fontMetrics.top
//                val x = if (mMaxCircleRadius > textWidth * 5) {
//                    mLineEndX - mMaxCircleRadius / 2 - textWidth / 2
//                } else {
//                    mCentreX + textWidth / 3f
//                }
//                canvas.drawText(mDistanceText, x, mCentreY - textHeight * 2, mTextPaint)

                val x = if (mCentreX - mMaxCircleRadius > textWidth + textHeight / 2) {
                    mCentreX - mMaxCircleRadius - textWidth - textHeight / 2
                } else {
                    mCentreX - mMaxCircleRadius + textHeight / 2
                }
                canvas.drawText(mDistanceText, x, mCentreY + textHeight / 4, mTextPaint)
            }

            mZoomBitmap?.apply {
                canvas.drawBitmap(this, mLineEndX - width / 2, mLineEndY - height / 2, null)
            }
        }
    }

    fun setOnCircleViewScaleClickListener(onCircleViewScaleClickListener: OnCircleViewScaleClickListener) {
        mScaleClickListener = onCircleViewScaleClickListener
    }

    /**
     * 设置圆的半径 单位dp
     */
    private fun setCircleRadius(dp: Int) {
        mMaxCircleRadius = QMUIDisplayHelper.dpToPx(dp).toFloat()
        invalidate()
    }

    /**
     * 设置圆的半径 单位px
     */
    fun setCircleRadiusPx(px: Float) {
        mMaxCircleRadius = px
        invalidate()
    }

    /**
     * 设置默认的半径
     */
    fun initDefaultRadius(dp: Int = 80) {
        if (dp <= 0) return
        setCircleRadius(dp)
    }

    fun setCentreXY(point: Point) {
        point.apply {
            if (mCentreX != x.toFloat() || mCentreY != y.toFloat()) {
                mCentreX = x.toFloat()
                mCentreY = y.toFloat()
                isNeedMeasure = false
                invalidate()
            }
        }
    }

//    private fun getCentreX() = mCentreX
//    private fun getCentreY() = mCentreY
//
//    private fun getLineEndX() = mLineEndX
//    private fun getLineEndY() = mLineEndY

    /**
     * 获取圆心点
     */
    fun getCircleCentrePoint() = Point(
        mCentreX.toInt(), mCentreY.toInt()
    )

    /**
     * 获取圆形直虚线的最后一个点
     */
    fun getCircleLineEndPoint() = Point(
        mLineEndX.toInt(), mLineEndY.toInt()
    )

    /**
     * 获取圆形直虚线的左边最开始的一个点
     */
    fun getCircleLineStartPoint() = Point(
        (mLineEndX - mMaxCircleRadius * 2).toInt(), mLineEndY.toInt()
    )

    /**
     * 设置显示的距离
     */
    fun setShowDisDistance(distance: String) {
        mDistanceText = distance
        invalidate()
    }

    /**
     * 设置隐藏显示距离文字
     */
    fun setShowHideDisDistance(show: Boolean) {
        if (isShowDistance != show) {
            isShowDistance = show
            invalidate()
        }
    }

    /**
     * 设置边框颜色和图片
     */
    fun setColorAndImage(
        context: Context,
        dashedColorRes: Int = 0,
        fillBgColorRes: Int = 0,
        locationDrawableRes: Int = 0,
        zoomDrawableRes: Int = 0,
        disTextColorRes: Int = 0
    ) {
        var isRefresh = false
        if (dashedColorRes > 0) {
            mDashedColor = ContextCompat.getColor(context, dashedColorRes)
            mPaint.color = mDashedColor
            isRefresh = true
        }
        if (fillBgColorRes > 0) {
            mFillBgColor = ContextCompat.getColor(context, fillBgColorRes)
            mInsideCirclePaint.color = mFillBgColor
            isRefresh = true
        }
        if (locationDrawableRes > 0) {
            mLocationBitmap = ImageUtil.getBitmapFromDrawableAndSvg(context, locationDrawableRes)
            isRefresh = true
        }
        if (zoomDrawableRes > 0) {
            mZoomBitmap = ImageUtil.getBitmapFromDrawableAndSvg(context, zoomDrawableRes)
            isRefresh = true
        }
        if (disTextColorRes > 0) {
            mTextPaint.color = ContextCompat.getColor(context, disTextColorRes)
            isRefresh = true
        }
        if (isRefresh) invalidate()
    }

    private var mScalingX = 0f

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                val x = event.x
                val y = event.y
                mZoomBitmap?.apply {
                    if (x in mLineEndX - width..mLineEndX + width && y in mLineEndY - height..mLineEndY + height) {
                        isScale = true
                        mOldX = x
                        return true
                    } else if (mRectF.contains(x, y)) {
                        isDrag = true
                        mOldX = x
                        mOldY = y
                        mPaint.strokeWidth = QMUIDisplayHelper.dpToPx(3).toFloat()
                        mScaleClickListener?.circleStartDragClick()
                        invalidate()
                        return true
                    }
                }
            }

            MotionEvent.ACTION_MOVE -> {
                val x = event.x
                val y = event.y
                if (isScale) {
                    val transformX = x - mOldX
                    val circleRadius = mMaxCircleRadius + transformX
                    //限制缩放不能太小
                    if (mLimitRadius == 0f && circleRadius < mLocationBitmap!!.height / 2f) {
                        return true
                    } else if (circleRadius < mLimitRadius) {
                        return true
                    }
                    mMaxCircleRadius = circleRadius
                    mOldX = x
                    if (abs(x - mScalingX) > 1) {
                        mScalingX = x
                        mScaleClickListener?.circleScalingClick()
                    }
                    invalidate()
                    return true
                } else if (isDrag) {
                    val transformX = x - mOldX
                    val transformY = y - mOldY
                    mCentreX += transformX
                    mCentreY += transformY
                    mOldX = x
                    mOldY = y
                    invalidate()
                    return true
                }
            }

            MotionEvent.ACTION_UP -> {
                if (isScale) {
                    mScaleClickListener?.circleScaleEndClick()
                    isScale = false
                } else if (isDrag) {
                    mScaleClickListener?.circleEndDragClick()
                    isDrag = false
                    mPaint.strokeWidth = QMUIDisplayHelper.dpToPx(1).toFloat()
                    invalidate()
                }
            }
        }
        return super.onTouchEvent(event)
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        LogUtil.e("${javaClass.canonicalName}视图销毁")
        if (null != mLocationBitmap) {
            mLocationBitmap?.recycle()
            mLocationBitmap = null
        }
        if (null != mZoomBitmap) {
            mZoomBitmap?.recycle()
            mZoomBitmap = null
        }
    }
}
