package com.gh.gamecenter.gamedetail.accelerator

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.view.updateLayoutParams
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.databinding.LayoutAcceleratorGuidePageBinding

class AcceleratorGuideView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    def: Int = 0
) : FrameLayout(context, attrs, def) {

    private val binding: LayoutAcceleratorGuidePageBinding

    private val rect = Rect()

    private var _isShowing = false
    val isShowing: Boolean
        get() = _isShowing

    private var isCanDismiss = false

    private val guideBackgroundColor =
        com.gh.gamecenter.common.R.color.black_alpha_60.toColor(context)

    private val xfermode by lazy {
        val mode = PorterDuff.Mode.CLEAR
        PorterDuffXfermode(mode)
    }

    private val paint by lazy {
        Paint().apply {
            color = Color.YELLOW
            isAntiAlias = true
            isDither = true
        }
    }

    private var onStartSpeed: (() -> Unit)? = null

    init {
        val inflater = LayoutInflater.from(context)
        binding = LayoutAcceleratorGuidePageBinding.inflate(inflater, this, true)

        binding.root.setOnClickListener {
            // 点击透明区域消失
            dismiss()
        }

        binding.clContainer.setOnClickListener {
            //覆盖外部点击事件，点击此区域 guideView 不消失
        }
        binding.vIKnow.setOnClickListener {
            dismiss()
        }

        binding.vSpeed.setOnClickListener {
            dismiss()
            onStartSpeed?.invoke()
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, left, top, right, bottom)

        val bottom = rect.bottom
        val top = bottom - binding.clContainer.height
        val right = rect.right + BORDER_WIDTH.dip2px()
        val left = right - binding.clContainer.width
        binding.clContainer.layout(left, top, right, bottom)
    }

    override fun dispatchDraw(canvas: Canvas) {

        val saveCount = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), paint)
        paint.color = guideBackgroundColor
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)

        onDrawDecoration(canvas)
        paint.xfermode = xfermode

        canvas.drawRoundRect(
            RectF(rect),
            HIGH_LIGHT_RADIUS.dip2px().toFloat(),
            HIGH_LIGHT_RADIUS.dip2px().toFloat(),
            paint
        )

        paint.xfermode = null
        canvas.restoreToCount(saveCount)

        super.dispatchDraw(canvas)
    }

    private fun onDrawDecoration(canvas: Canvas) {
        paint.color = com.gh.gamecenter.common.R.color.ui_surface.toColor(context)
        val border = BORDER_WIDTH.dip2px()
        val radius = HIGH_LIGHT_RADIUS.dip2px().toFloat()
        val dRectF = RectF(
            rect.left.toFloat() - border,
            rect.top.toFloat() - border,
            rect.right.toFloat() + border,
            rect.bottom.toFloat() + border
        )
        canvas.drawRoundRect(dRectF, radius, radius, paint)
    }

    private fun setHighLightRect(newRect: Rect) {
        rect.set(newRect)
        binding.vSpeed.updateLayoutParams {
            width = rect.width()
        }
    }

    fun show(anchor: View, activity: Activity, block: () -> Unit) {
        onStartSpeed = block
        val newRect = getLocationInWindow(anchor)
        val content = activity.window.decorView as ViewGroup
        layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        setHighLightRect(newRect)

        content.addView(this)

        setOnClickListener {
            if (isCanDismiss) {
                dismiss()
            }
        }
        setOnClickListener {

        }
        _isShowing = true

        isCanDismiss = false

        AppExecutor.uiExecutor.executeWithDelay({
            isCanDismiss = true
        }, SHOW_MIN_DURATION)
    }

    fun dismiss() {
        (parent as? ViewGroup)?.removeView(this)
        _isShowing = false
        onDismissListener?.invoke()
    }

    private var onDismissListener: (() -> Unit)? = null
    fun setDismissListener(listener: () -> Unit) {
        onDismissListener = listener
    }

    private fun getLocationInWindow(anchor: View): Rect {
        val result = Rect()
        val pos = IntArray(2)
        anchor.getLocationInWindow(pos)
        result.left = pos[0]
        result.top = pos[1]
        result.right = result.left + anchor.width
        result.bottom = result.top + anchor.height
        return result
    }

    companion object {

        private const val BORDER_WIDTH = 4F
        private const val HIGH_LIGHT_RADIUS = 100F
        private const val SHOW_MIN_DURATION = 500L
    }
}