package com.zxhl.main.page.activity

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.loper7.date_time_picker.StringUtils
import com.zlw.main.recorderlib.RecordManager
import com.zlw.main.recorderlib.recorder.RecordHelper
import com.zlw.main.recorderlib.recorder.listener.RecordResultListener
import com.zlw.main.recorderlib.recorder.listener.RecordStateListener
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.uc.UserInfo
import com.zxhl.cms.runtimepermission.NicePermission
import com.zxhl.cms.runtimepermission.NicePermissionListener
import com.zxhl.cms.widget.ChatDialogUtils
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.main.R
import com.zxhl.main.page.contract.VoiceContract
import com.zxhl.main.page.presenter.VoicePresenter
import kotlinx.android.synthetic.main.activity_layout_voice.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class VoiceActivity : BaseActivity(), VoiceContract.View {
    private var mPresenter: VoicePresenter? = null
    private var url: String? = ""
    private var mMediaPlayer: MediaPlayer? = null
    private var recodeFile: File? = null
    private var mHandler: Handler? = null
    private var count: Int = 0
    private var mLoading: LoadingDialog? = null

    companion object {
        val PERMISSIONS = arrayOf(
            Constant.Permission.PERMISSION_RECORD_AUDIO,
            Constant.Permission.PERMISSION_STORAGE, Constant.Permission.PERMISSION_READ_STORAGE
        )
    }

    override fun onClick(v: View?) {

    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_voice
    }

    private val runnable: Runnable = object : Runnable {
        override fun run() {
            count++
            if (count < 10) {
                id_tv_luzhi_count_time?.text = "0:" + "0${count}"
                id_tv_luzhi_end_time?.text = "0:" + "0${count}"
            } else {
                id_tv_luzhi_count_time?.text = "0:" + "${count}"
                id_tv_luzhi_end_time?.text = "0:" + "${count}"
                if (count == 28) {
                    stopRecord()
                }

            }
            mHandler?.postDelayed(this, 1000)
        }
    }

    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPresenter = VoicePresenter(this)
        Log.e("MXl","URL:"+SettingPreference.getVoiceUrl())
        if (!TextUtils.isEmpty(SettingPreference.getVoiceUrl())) {
            //当前已有录音
            haveVoice()
        } else {
            noVoice()
        }
        mMediaPlayer = MediaPlayer()
        id_img_back?.setOnClickListener {
            finish()
        }
        mHandler = Handler()
        id_img_luzhi?.setOnClickListener {
            //开始录制
            checkPermission()
        }
        id_img_luzhi_zhong?.setOnClickListener {
            //录制中点停止
            if (count < 3) {
                showToast("语音时长要在3-28秒之间哦～")
                return@setOnClickListener
            }
            stopRecord()
        }
        id_tv_chong_lu?.setOnClickListener {
            //重录
            count = 0
            id_tv_luzhi_count_time?.text = "0:" + "0${count}"
            if (mHandler != null) {
                mHandler?.removeCallbacks(runnable)
            }
            if (mMediaPlayer != null) {
                if (mMediaPlayer!!.isPlaying) {
                    mMediaPlayer!!.stop()
                    mMediaPlayer?.reset()
                }
            }
            id_rl_recording_end?.visibility = View.GONE
            id_tv_save_audio?.visibility = View.VISIBLE
            id_rl_start_recording.visibility = View.VISIBLE
            SettingPreference.setVoiceUrl("")
            SettingPreference.setVoiceTime("")
        }
        id_tv_save_audio?.setOnClickListener {
            //保存
            val voiceFile = File(url)
            val requestvoiceFile =
                RequestBody.create("multipart/form-data".toMediaTypeOrNull(), voiceFile)
            val voicefileBody =
                MultipartBody.Part.createFormData("voice", voiceFile.name, requestvoiceFile)
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            mPresenter?.updateUserVoice("${count}", voicefileBody)
//            SettingPreference.setLocalUrl(url)
//            SettingPreference.setVoiceUrl(url)
//            SettingPreference.setVoiceTime(count.toString())

//            if (mMediaPlayer != null) {
//                mMediaPlayer?.stop()
//                mMediaPlayer?.release()
//            }
        }
        id_img_luzhi_play?.setOnClickListener {
            if (!TextUtils.isEmpty(SettingPreference.getVoiceUrl())) {
                playAudio(SettingPreference.getVoiceUrl())
            } else {
                playAudio(url)
            }


        }
        RecordManager.getInstance().setRecordStateListener(object : RecordStateListener {
            override fun onStateChange(state: RecordHelper.RecordState?) {
                when (state) {
                    RecordHelper.RecordState.IDLE -> {
                        //空闲状态
                        Log.e("MXL", "录音空闲")
                    }
                    RecordHelper.RecordState.RECORDING -> {
                        //录音状态
                        mHandler?.postDelayed(runnable, 1000);
                        Log.e("MXL", "录音开始")
                    }
                    RecordHelper.RecordState.STOP -> {
                        //停止状态
                        Log.e("MXL", "录音停止")
                    }
                    RecordHelper.RecordState.FINISH -> {
                        //完成状态
                        Log.e("MXL", "录音结束")
                    }

                }

            }

            override fun onError(error: String?) {

            }

        })
        RecordManager.getInstance().setRecordResultListener(object : RecordResultListener {
            override fun onResult(result: File?) {
                recodeFile = result
                url = result?.path
            }

        })
    }

    fun playAudio(url: String?) {
        try {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.stop()
            }
            mMediaPlayer?.reset()
            mMediaPlayer?.isLooping = false
            mMediaPlayer?.setDataSource(this, Uri.parse(url))
            mMediaPlayer?.prepareAsync()
            mMediaPlayer?.setOnPreparedListener {
                mMediaPlayer?.start()
                id_img_luzhi_play?.setImageResource(R.drawable.icon_luzhijieshu_bofang)
            }
            mMediaPlayer?.setOnCompletionListener {
                id_img_luzhi_play?.setImageResource(R.drawable.icon_luzhijieshu)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun startRecord() {
        id_rl_start_recording?.visibility = View.GONE
        id_rl_recording?.visibility = View.VISIBLE
        RecordManager.getInstance().start()
    }

    fun stopRecord() {
        RecordManager.getInstance().stop()
        if (mHandler != null) {
            mHandler?.removeCallbacks(runnable)
        }
        id_rl_recording?.visibility = View.GONE
        id_rl_recording_end?.visibility = View.VISIBLE

    }

    fun haveVoice() {
        if (!TextUtils.isEmpty(SettingPreference.getVoiceTime())) {
            var s = SettingPreference.getVoiceTime()
            if (s?.contains("s") == false) {
            } else {
                s=s.replace("s","")
            }
            if (s.toString().toInt() < 10) {
                id_tv_luzhi_end_time?.text = "0:0${s}"
            } else {
                id_tv_luzhi_end_time?.text = "0:${s}"
            }

            id_rl_start_recording?.visibility = View.GONE
            id_rl_recording?.visibility = View.GONE
            id_rl_recording_end?.visibility = View.VISIBLE
            id_tv_save_audio?.visibility = View.GONE
        }

    }

    fun noVoice() {
        id_rl_start_recording?.visibility = View.VISIBLE
        id_rl_recording?.visibility = View.GONE
        id_rl_recording_end?.visibility = View.GONE
        id_tv_save_audio?.visibility = View.VISIBLE
    }

    fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NicePermission(this, object : NicePermissionListener {
                override fun onGranted() {
                    startRecord()
                }

                override fun onRefused() {
                    ChatDialogUtils.showPermissionDialog(mActivity as Activity, "请开启录音和存储权限")
                }
            }).requestPermission(
                *arrayOf(
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
            )
        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            107 -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startRecord()
                } else {
                    // 权限被用户拒绝了。
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.RECORD_AUDIO
                        )
                    ) {
                        //提示用户前往设置界面自己打开权限
                        Toast.makeText(this, "请前往设置界面打开权限", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mMediaPlayer != null) {
            mMediaPlayer?.stop()
            mMediaPlayer?.release()
        }
    }


    override fun updateVoiceSuc(result: UserInfo?) {
        mLoading?.setResult(true, "保存成功", 1000)
        if(result!=null){
            Log.e("MXL","保存录音成功")
            SettingPreference.setVoiceUrl(result.voice)
            SettingPreference.setVoiceTime(result.voiceTime)
        }

        id_tv_save_audio?.visibility = View.INVISIBLE

        //   id_img_luzhi_play?.setImageResource(R.drawable.icon_luzhijieshu)
    }

    override fun updateVoiceFail() {
        mLoading?.setResult(false, "保存失败", 1000)
    }
}