package com.audio.record.screen.test.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.MediaRecorder
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.CountDownTimer
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RemoteViews
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.audio.record.screen.test.R
import com.audio.record.screen.test.activity.MainActivity1
import com.audio.record.screen.test.activity.PlayActivity
import com.audio.record.screen.test.activity.ScreenPermissionActivity
import com.audio.record.screen.test.activity.ScreenshotAnimActivity
import com.audio.record.screen.test.tool.Common
import com.audio.record.screen.test.tool.ConstValue
import com.audio.record.screen.test.tool.DraggableViewHelper
import com.audio.record.screen.test.tool.Extend.dpToPx
import com.audio.record.screen.test.tool.Extend.pxToDp
import com.audio.record.screen.test.tool.ScreenCaptureHelper
import com.audio.record.screen.test.tool.VideoFileHelper
import com.audio.record.screen.test.view.CountDownFloatingManager
import java.lang.ref.WeakReference

class ScreenRecordService : Service() {

    private var lifecycleOwner: CustomLifecycleOwner? = null

    private var isBallViewAdded = false
    private var isBallExpandViewAdded = false
    private var isScreenshotViewAdded = false
    private var isWebcamViewAdded = false
    private var isRecordViewAdded = false

    //前置摄像头View
    private var frontCameraView: View? = null
    private lateinit var cameraView: PreviewView

    //悬浮球View
    private var ballView: View? = null
    private var imIconVideo: ImageView? = null
    private var smallLayoutRecording: LinearLayout? = null
    private var smallTvTime: TextView? = null


    //悬浮球展开View
    private var ballViewExpand: View? = null
    private var imRecord: ImageView? = null
    private var tvRecordTime: TextView? = null
    private var imNoAudioRecord: ImageView? = null
    private var imScreenshot: ImageView? = null

    //截屏View
    private var screenshotView: View? = null

    //倒计时
    private var countdownView: View? = null
    private lateinit var countDownHandler: Handler
    private var index = 0

    //录屏成功View
    private var recordCompleteView: View? = null

    private val windowManager by lazy { getSystemService(WINDOW_SERVICE) as WindowManager }
    private lateinit var layoutParamsBallExpand: WindowManager.LayoutParams
    private lateinit var layoutParamsBall: WindowManager.LayoutParams
    private lateinit var layoutParamsScreenshot: WindowManager.LayoutParams
    private lateinit var layoutParamsCameraView: WindowManager.LayoutParams
    private lateinit var layoutParamsCountDown: WindowManager.LayoutParams
    private lateinit var layoutParamsRecordView: WindowManager.LayoutParams
    private lateinit var screenWH: Pair<Int, Int>


    //截屏
    private lateinit var screenCaptureLauncher: ActivityResultLauncher<Intent>
    private lateinit var mediaProjectionManager: MediaProjectionManager


    private var callbackRef: FloatingCallback? = null

    //截屏
    var mIntent: Intent? = null
    private var mCode: Int = 0

    private lateinit var mediaRecorder: MediaRecorder
    private lateinit var tmpVideoUri: Uri
    private lateinit var videoName: String
    private var tmpVideoPfd: ParcelFileDescriptor? = null

    //当前录制是否带音频
    private var isWithAudio = false

    private val callbacks = mutableListOf<WeakReference<FloatingCallback>>()
    private var countDownTimer: CountDownTimer? = null

    //录制状态标志  true 录制中
    private var mRecordingStatus = -1

    //录制时间监听相关
    private var recordingStartTime: Long = 0L     // 本次录制开始时间
    private val mRecorderHandler = Handler(Looper.getMainLooper())
    private val updateInterval = 1000L
    private var pauseStartTime: Long = 0L        // 本次暂停的开始时间
    private var totalPausedTime: Long = 0L       // 所有暂停段的总时间

    //当前是否处于录制暂停
    private var isPause = false
    private lateinit var virtualDisplay: VirtualDisplay

    //悬浮球点击进行的动作 type_record_audio/type_record_without_audio/type_screenshot
    private var ballType: Int? = null

    private var mediaProjection: MediaProjection? = null

    private val timeUpdateRunnable = object : Runnable {
        override fun run() {

            val currentRecordingTimeInMillis =
                System.currentTimeMillis() - recordingStartTime - totalPausedTime
            val elapsed = currentRecordingTimeInMillis / 1000
            val onRecordingTimeChanged = Common.onRecordingTimeChanged(elapsed)
            tvRecordTime?.text = onRecordingTimeChanged
            smallTvTime?.text = onRecordingTimeChanged
            callbacks.forEach {
                it.get()?.onUpdateRecordTime(onRecordingTimeChanged)
            }
            if (!isPause)
                mRecorderHandler.postDelayed(this, updateInterval)
        }
    }

    inner class FloatingBinder : Binder() {
        fun getService() = this@ScreenRecordService


        fun registerCallback(callback: FloatingCallback) {
            // 避免重复添加
            if (callbacks.any { it.get() == callback }) return
            callbacks.add(WeakReference(callback))
            Common.showLog("=======registerCallback  callback=${callback}")
        }

        fun unregisterCallback(callback: FloatingCallback) {
            callbacks.removeAll {
                it.get() == null || it.get() == callback
            }
            Common.showLog("=======unregisterCallback  callback=${callback}")
        }
    }

    /**
     * 设置当前录制是否带音频
     */
    fun setIsAudio(audio: Boolean) {
        isWithAudio = audio
        Common.showLog("Service---isWithAudio=${isWithAudio}")
    }


    override fun onCreate() {
        super.onCreate()
        Common.showLog("Service---onCreate")
        lifecycleOwner = CustomLifecycleOwner()
        screenWH = Common.getScreenWH(this)

        mediaProjectionManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager


    }

    fun createMediaProjection(code: Int, m: Intent) {
        mIntent = m
        mCode = code
//        mediaProjection = mediaProjectionManager.getMediaProjection(code, m)
        ballType?.let {
            when (it) {
                ConstValue.type_record_without_audio -> {
                    isWithAudio = false
                    val arrayOf = arrayOf("3", "2", "1")
                    showCountDownView(arrayOf)
                }

                ConstValue.type_record_audio -> {
                    Common.showLog("Service--- 录制带音频的视频")
                    isWithAudio = true
                    val arrayOf = arrayOf("3", "2", "1")
                    showCountDownView(arrayOf)
                }

                ConstValue.type_screenshot -> {
                    startScreenshot(isScreenshotViewAdded)
                }
            }
            ballType = null
        }
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Common.showLog("Service---onStartCommand")
        lifecycleOwner?.onStart()
        // 初始化 MediaProjection、MediaRecorder 逻辑等
        // TODO:  onStartCommand


        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder {
        lifecycleOwner?.onStart()
        Common.showLog("Service---onBind")
        startForeground(1, createNotification())
        return FloatingBinder()
    }


    //构建通知栏
    private fun createNotification(): Notification {

        val remoteViews = RemoteViews(packageName, R.layout.custom_notification)
        val channelId = "screen_record_channel"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "录屏",
                NotificationManager.IMPORTANCE_LOW
            )
            getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
        }

        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("")
            .setContentText("")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCustomContentView(remoteViews)
            .setCustomBigContentView(remoteViews)
            .setSmallIcon(R.mipmap.logo)
            .build()
    }


    /**
     * 开始截屏
     */
    private fun startScreenshot(showView: Boolean) {
        // TODO: 开始截屏
        mIntent?.let { intent ->
            mediaProjectionManager.getMediaProjection(mCode, intent)?.let { mediaProjection ->
                hideScreenshot()
                val intent = Intent(this, ScreenshotAnimActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
                ScreenCaptureHelper.startScreenCapture(this, mediaProjection) { bit ->
                    callbacks.forEach {
                        it.get()?.onRefreshBitmap(bit)
                    }
                    //截屏完成
                    if (showView)
                        showScreenshot()
                }
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun showCameraView() {
        if (frontCameraView == null) {
            frontCameraView =
                LayoutInflater.from(this).inflate(R.layout.floating_front_camera, null)
            layoutParamsCameraView = getLayoutParams()
            layoutParamsCameraView.gravity = Gravity.TOP or Gravity.START
            cameraView = frontCameraView!!.findViewById<PreviewView>(R.id.previewView)
            startFrontCamera(cameraView)
            DraggableViewHelper.attachToWindow(
                frontCameraView!!,
                layoutParamsCameraView,
                windowManager,
                true
            )

        }
        if (!isWebcamViewAdded) {
            windowManager.addView(frontCameraView, layoutParamsCameraView)
            isWebcamViewAdded = true
        }


    }


    override fun onDestroy() {
        super.onDestroy()
        hideFrontCamera()  // 自动清除
        hideBall()
        hideScreenshot()
        hideBallExpand()
        hideRecordCompleteView()
        ballViewExpand = null
        recordCompleteView = null
        frontCameraView = null
        ballView = null
        screenshotView = null
        callbackRef = null
        lifecycleOwner?.onStop()
        Common.showLog("Service---onDestroy")
    }

    fun startFrontCamera(view: PreviewView) {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()

            // 设置预览
            val preview = Preview.Builder().build().also {
                it.surfaceProvider = view.surfaceProvider
            }

            // 前置摄像头选择器
            val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                .build()

            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(lifecycleOwner!!, cameraSelector, preview)
            } catch (e: Exception) {
                Common.showLog("绑定前置摄像头失败==$e")
            }

        }, ContextCompat.getMainExecutor(this))
    }


    //显示悬浮球
    fun showBall() {
        if (ballView == null) {
            ballView = LayoutInflater.from(this).inflate(R.layout.floating_ball, null)
            layoutParamsBall = getLayoutParams()
            val size = Common.dpToPx(36, this)
            layoutParamsBall.gravity = Gravity.TOP or Gravity.START
            layoutParamsBall.x = screenWH.first - size - 20
            layoutParamsBall.y = screenWH.second / 2 - size.div(2)  // 居中
            smallLayoutRecording = ballView!!.findViewById<LinearLayout>(R.id.layout_recording)
            imIconVideo = ballView!!.findViewById<ImageView>(R.id.image)
            smallTvTime = ballView!!.findViewById<TextView>(R.id.tv_small_time)


            DraggableViewHelper.attachToWindow(ballView!!, layoutParamsBall, windowManager, true) {
                hideBall()
                showBallExpand()
            }
            Common.showLog("-------layoutParamsBall.x=${layoutParamsBall.x}     layoutParamsBall.y=${layoutParamsBall.y}")
        }
        if (!isBallViewAdded&&!isBallExpandViewAdded) {
            windowManager.addView(ballView, layoutParamsBall)
            isBallViewAdded = true
        }
    }


    fun showBallExpand() {
        if (ballViewExpand == null) {
            ballViewExpand = LayoutInflater.from(this).inflate(R.layout.floating_ball_expand, null)
            layoutParamsBallExpand = getLayoutParams()
            layoutParamsBallExpand.gravity = Gravity.TOP or Gravity.START
            imRecord = ballViewExpand!!.findViewById<ImageView>(R.id.ic_record)
            tvRecordTime = ballViewExpand!!.findViewById<TextView>(R.id.tv_record_time)
            imNoAudioRecord = ballViewExpand!!.findViewById<ImageView>(R.id.ic_without_audio)
            imScreenshot = ballViewExpand!!.findViewById<ImageView>(R.id.ic_screenshot)
            ballViewExpand!!.findViewById<ImageView>(R.id.ic_home).setOnClickListener {


                val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
                launchIntent?.apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(this)
                }


            }

            imRecord?.setOnClickListener {
                it.isSelected.let { select ->
                    if (!select) {
                        //录制带音频的视频
                        ballType = ConstValue.type_record_audio
                        intentPermission(true)
                    } else {
                        //录制完成
                        stopRecording()
                    }
                }
            }
            imNoAudioRecord?.setOnClickListener {
                // TODO:
                when (mRecordingStatus) {
                    ConstValue.status_recording -> {
                        //暂停录制
                        pauseRecording()
                    }

                    ConstValue.status_pause -> {
                        //继续录制
                        resumeRecording()
                    }

                    else -> {
                        // 开始录制没有声音的视频
                        ballType = ConstValue.type_record_without_audio
                        intentPermission(false)
                    }
                }

            }

            imScreenshot?.setOnClickListener {
                ballType = ConstValue.type_screenshot
                intentPermission(false)

            }
        }

        if (!isBallExpandViewAdded) {
            val size = Common.dpToPx(36, this)
            val aWidthPx = Common.dpToPx(55, this)
            val aHeightPx = Common.dpToPx(250, this)
            // 转换 B 的宽高为像素
            val bWidthPx = size
            val bHeightPx = size

            // 计算 B 的中心点坐标
            val bCenterX = layoutParamsBall.x + bWidthPx / 2
            val bCenterY = layoutParamsBall.y + bHeightPx / 2

            // 让 A 的左上角从 B 的中心点出发（居中显示）
            var aX = bCenterX - aWidthPx / 2
            var aY = bCenterY - aHeightPx / 2

            val (screenWidth, screenHeight) = Common.getScreenWH(this)
            // 修正边界：防止 A 悬浮窗超出屏幕边界
            aX = aX.coerceIn(0, screenWidth - aWidthPx)
            aY = aY.coerceIn(0, screenHeight - aHeightPx)

            if (aX >= screenWidth / 2) {
                layoutParamsBallExpand.x = aX - 10.dpToPx(this)

            } else {
                layoutParamsBallExpand.x = aX + 10.dpToPx(this)

            }
            layoutParamsBallExpand.y = aY
            windowManager.addView(ballViewExpand, layoutParamsBallExpand)
            isBallExpandViewAdded = true
            delayRemove {
                Common.showLog("-------切换ball显示")
                hideBallExpand()
                showBall()
            }
        }
    }


    /**
     * 3秒后自动隐藏
     */
    private fun delayRemove(onFinish: (() -> Unit)?) {
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(3000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                onFinish?.invoke()
                countDownTimer = null
            }
        }
        countDownTimer?.start()
    }


    //显示截屏
    fun showScreenshot() {
        if (screenshotView == null) {
            screenshotView = LayoutInflater.from(this).inflate(R.layout.floating_screenshot, null)
            layoutParamsScreenshot = getLayoutParams()

            val size = Common.dpToPx(36, this)
            layoutParamsScreenshot.gravity = Gravity.TOP or Gravity.START
            layoutParamsScreenshot.x = 20 // 右侧偏移
            layoutParamsScreenshot.y = screenWH.second / 2 - size.div(2)  // 居中

            DraggableViewHelper.attachToWindow(
                screenshotView!!,
                layoutParamsScreenshot,
                windowManager,
                true
            ) {
                startScreenshot(true)
            }
        }
        if (!isScreenshotViewAdded) {
            windowManager.addView(screenshotView, layoutParamsScreenshot)
            isScreenshotViewAdded = true
        }
    }


    //显示截屏
    fun showRecordView() {
        if (recordCompleteView == null) {
            recordCompleteView =
                LayoutInflater.from(this).inflate(R.layout.floating_record_complete, null)
            layoutParamsRecordView = getLayoutParams()
            layoutParamsRecordView.gravity = Gravity.CENTER
            val imClose =
                recordCompleteView!!.findViewById<ImageView>(R.id.close).setOnClickListener {
                    hideRecordCompleteView()
                }
            recordCompleteView!!.findViewById<FrameLayout>(R.id.layout_video).setOnClickListener {
                // TODO:  跳到播放页面
                hideRecordCompleteView()
                val intent = Intent(this, PlayActivity::class.java).apply {
                    putExtra(PlayActivity.KEY_URI, tmpVideoUri)
                    putExtra(PlayActivity.KEY_name, videoName)
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                this.startActivity(intent)

            }
        }
        if (!isRecordViewAdded) {
            val videoThumbnail = Common.getVideoThumbnail(tmpVideoPfd!!)
            Common.showLog("--------------videoThumbnail=${videoThumbnail}")
            val thumb = recordCompleteView!!.findViewById<ImageView>(R.id.image)
            thumb.setImageBitmap(videoThumbnail)
            windowManager.addView(recordCompleteView, layoutParamsRecordView)
            isRecordViewAdded = true
            delayRemove {
                hideRecordCompleteView()
            }
        }
    }

    fun hideFrontCamera() {
        frontCameraView?.let {
            try {
                if (isWebcamViewAdded) {
                    windowManager.removeView(it)
                    isWebcamViewAdded = false
                }

            } catch (_: Exception) {
            }
        }
//        frontCameraView = null
    }

    fun hideBallExpand() {
        ballViewExpand?.let {
            try {
                if (isBallExpandViewAdded) {
                    windowManager.removeView(it)
                    isBallExpandViewAdded = false
                }

            } catch (_: Exception) {
            }
        }
//        frontCameraView = null
    }

    //隐藏录制预览View
    fun hideRecordCompleteView() {
        recordCompleteView?.let {
            try {
                if (isRecordViewAdded) {
                    windowManager.removeView(it)
                    isRecordViewAdded = false
                }

            } catch (_: Exception) {
            }
        }
//        frontCameraView = null
    }

    //隐藏悬浮球
    fun hideBall() {
        ballView?.let {
            try {
                windowManager.removeView(it)
                isBallViewAdded = false
            } catch (_: Exception) {
            }
        }
//        ballView = null
    }

    //隐藏截屏
    fun hideScreenshot() {
        screenshotView?.let {
            try {
                windowManager.removeView(it)
                isScreenshotViewAdded = false
            } catch (_: Exception) {
            }
        }
//        screenshotView = null
    }


    //显示倒计时
    fun showCountDownView(countdownValues: Array<String>) {
        if (countdownView == null) {
            countdownView =
                LayoutInflater.from(this).inflate(R.layout.floating_view_countdown, null)
            layoutParamsCountDown = getLayoutParams()
            layoutParamsCountDown.gravity = Gravity.CENTER

        }
        if (countdownView?.windowToken == null) {
            Common.showLog("Service--- 录制带音频的视频 addView")
            windowManager.addView(countdownView, layoutParamsCountDown)
            val tvCountdown = countdownView!!.findViewById<TextView>(R.id.tv_countdown)
            index = 0
            countDownHandler = Handler(Looper.getMainLooper())
            animateNext(countdownValues, tvCountdown) {
                //倒计时结束后，开启录制
                Common.showLog("Service--- 倒计时结束")
                hideCountDown()
                mIntent?.let { intent ->
                    mediaProjectionManager.getMediaProjection(mCode, intent)
                        ?.let { media ->
                            mediaProjection = media
                            startRecording()
                            callbacks.forEach {
                                it.get()?.onStartRecording()
                            }
                        }
                }

            }
        }


    }

    private fun animateNext(
        countdownValues: Array<String>,
        tvCountdown: TextView,
        onFinish: (() -> Unit)? = null
    ) {
        if (index >= countdownValues.size) {
            CountDownFloatingManager.remove(windowManager)
            onFinish?.invoke()
            return
        }

        tvCountdown.text = countdownValues[index]
        tvCountdown.scaleX = 0f
        tvCountdown.scaleY = 0f
        tvCountdown.alpha = 0f

        tvCountdown.animate()
            .scaleX(1f).scaleY(1f)
            .alpha(1f)
            .setDuration(400)
            .setInterpolator(AccelerateDecelerateInterpolator())
            .withEndAction {
                countDownHandler?.postDelayed({
                    index++
                    animateNext(countdownValues, tvCountdown, onFinish)
                }, 600)
            }
            .start()
    }


    //移除倒计时View
    fun hideCountDown() {
        countDownHandler.removeCallbacksAndMessages(null)
        countdownView?.let {
            try {
                windowManager.removeView(it)
            } catch (e: Exception) {
                // view already removed
            }
        }
        countdownView = null
    }


    /**
     * 开启录制视频
     */
    fun startRecording() {
        Common.showLog("-------录屏中.....")
        // TODO:  录屏中.
        val fullScreenSize = Common.getFullScreenSize(this)
        val width = VideoFileHelper.alignTo16(fullScreenSize.first)
        val height = VideoFileHelper.alignTo16(fullScreenSize.second)
        initRecorder(width, height)
        mediaRecorder.start()
        mRecordingStatus = ConstValue.status_recording
        updateBall()
        recordingStartTime = System.currentTimeMillis()
        totalPausedTime = 0L
        mRecorderHandler.post(timeUpdateRunnable)

        mediaProjection?.let {
            it.registerCallback(object : MediaProjection.Callback() {
                override fun onStop() {
                    Common.showLog("MediaProjection 被系统或用户停止")
                    // 这里应该释放 MediaRecorder 和 VirtualDisplay 等
                    stopRecording()

                }
            }, Handler(Looper.getMainLooper()))
            virtualDisplay = it.createVirtualDisplay(
                "ScreenRecord",
                width, height, resources.displayMetrics.densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mediaRecorder.surface, object : VirtualDisplay.Callback() {
                    override fun onPaused() {
                        super.onPaused()
                        Common.showLog("--VirtualDisplay.Callback..onPaused...")
                    }

                    override fun onResumed() {
                        super.onResumed()
                        Common.showLog("--VirtualDisplay.Callback..onResumed...")
                    }

                    override fun onStopped() {
                        super.onStopped()
                        Common.showLog("--VirtualDisplay.Callback..onStopped...")
                    }
                }, null
            )
        }
    }


    private fun releaseAll() {
        if (::mediaRecorder.isInitialized) {
            try {
                mediaRecorder.stop()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            try {
                mediaRecorder.reset()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            try {
                mediaRecorder.release()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        try {
            virtualDisplay?.release()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        try {
            mediaProjection?.stop()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 暂停录制视频
     */
    fun pauseRecording() {
        // TODO:  暂停录制视频
        Common.showLog("-------暂停.....")
        mediaRecorder.pause()
        mRecordingStatus = ConstValue.status_pause
        updateBall()
        callbacks.forEach {
            it.get()?.onPauseRecord()
        }
        pauseStartTime = System.currentTimeMillis()
        isPause = true
    }

    /**
     * 继续录制视频
     */
    fun resumeRecording() {
        // TODO:  继续录制视频
        Common.showLog("------继续.....")

        mediaRecorder.resume()
        mRecordingStatus = ConstValue.status_recording
        updateBall()
        callbacks.forEach {
            it.get()?.onResumeRecord()
        }
        totalPausedTime += System.currentTimeMillis() - pauseStartTime
        isPause = false
        mRecorderHandler.post(timeUpdateRunnable)
    }

    /**
     * 录制状态更新
     */
    private fun updateBall() {
        // TODO:  录制状态更新
        when (mRecordingStatus) {
            ConstValue.status_recording -> {
                imNoAudioRecord?.run {
                    isSelected = true
                    isActivated = false

                }
                imRecord?.isSelected = true
                tvRecordTime?.isVisible = true

                imIconVideo?.isVisible = false
                smallLayoutRecording?.isVisible = true
            }

            ConstValue.status_pause -> {
                imNoAudioRecord?.run {
                    isSelected = false
                    isActivated = true
                }

                imIconVideo?.isVisible = false
                smallLayoutRecording?.isVisible = true
            }

            ConstValue.status_complete -> {
                imNoAudioRecord?.run {
                    isSelected = false
                    isActivated = false
                }

                imRecord?.isSelected = false
                tvRecordTime?.isVisible = false

                imIconVideo?.isVisible = true
                smallLayoutRecording?.isVisible = false
                hideBallExpand()
                showBall()
            }
        }
    }


    private fun initRecorder(width: Int, height: Int) {
        videoName = System.currentTimeMillis().toString()
        val (Uri, pfd) = VideoFileHelper.createVideoFile(this, Common.folderName, videoName)
        tmpVideoUri = Uri
        tmpVideoPfd = pfd
        mediaRecorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            MediaRecorder(applicationContext)
        } else {
            MediaRecorder()
        }.apply {
            if (isWithAudio) {
                setAudioSource(MediaRecorder.AudioSource.MIC)
            }
            setVideoSource(MediaRecorder.VideoSource.SURFACE)
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            setOutputFile(pfd?.fileDescriptor)
            setVideoSize(width, height)
            if (isWithAudio) {
                setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            }
            setVideoEncoder(MediaRecorder.VideoEncoder.H264)

            setVideoEncodingBitRate(8 * 1000 * 1000)
            setVideoFrameRate(30)
            prepare()
        }
    }


    fun getViewStatus() {
        callbacks.forEach {
            it.get()?.onRefreshViewShow(isWebcamViewAdded, isScreenshotViewAdded, isBallViewAdded||isBallExpandViewAdded)
        }
    }

    fun getRecordingStatus() {
        callbacks.forEach {
            it.get()?.onRefreshRecordingStatus(mRecordingStatus)
        }
    }

    fun stopRecording() {
        // TODO:  录屏完成
        mRecordingStatus = ConstValue.status_complete
        updateBall()
        Common.showLog("-------录屏完成.....")
        mRecorderHandler.removeCallbacks(timeUpdateRunnable)
        releaseAll()
        VideoFileHelper.markVideoFileCompleted(this, tmpVideoUri)
        showRecordView()
        callbacks.forEach {
            it.get()?.onStopRecord()
        }
    }

    private fun getLayoutParams(): WindowManager.LayoutParams {
        return WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,

            PixelFormat.TRANSLUCENT
        )

    }


    private fun intentPermission(requestAudio: Boolean) {
        val intent = Intent(this, ScreenPermissionActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.putExtra(ScreenPermissionActivity.key_with_audio, requestAudio)
        this.startActivity(intent)

    }

}