package com.zxhl.main.page.activity


import android.Manifest
import android.app.Activity
import android.graphics.ImageFormat
import android.hardware.Camera
import android.media.MediaPlayer
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.view.animation.AnimationUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.chat.StarMachEntity
import com.zxhl.cms.runtimepermission.NicePermission
import com.zxhl.cms.runtimepermission.NicePermissionListener
import com.zxhl.cms.utils.ChatCallback
import com.zxhl.cms.utils.ChatMessageChargeUtils
import com.zxhl.cms.utils.NoDoubleClickListener
import com.zxhl.cms.widget.ChatDialogUtils
import com.zxhl.main.R
import com.zxhl.main.page.contract.StarMachContract
import com.zxhl.main.page.presenter.StarMachPresenter
import kotlinx.android.synthetic.main.activity_layout_constell_reslut.*
import java.io.IOException

class ConstellReslutActivity : BaseActivity(), StarMachContract.View, Camera.PreviewCallback {
    private var mPresenter: StarMachPresenter? = null
    private var mediaPlayer: MediaPlayer? = null
    var Camerafb = 1
    private var mHandler: Handler? = null
    private var count: Int = 0
    private var ifCharge: Boolean = false

    /**
     * 创建Camera对象
     * 用来获取摄像头
     */
    var camera: Camera? = null


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

    override fun onClick(v: View?) {

    }

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

    override fun init() {
        mediaPlayer = MediaPlayer()
        mHandler = Handler()
        mPresenter = StarMachPresenter(this)
        mPresenter?.getStarMachReslut()
        checkPermission()
        id_img_close?.setOnClickListener {
            finish()
        }
        id_tv_next_girl?.setOnClickListener(object : NoDoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                mPresenter?.getStarMachReslut()
            }

        })
        id_img_xintiao.animation = AnimationUtils.loadAnimation(context, R.anim.button_scale_anim)

    }
    private var mCameraSuf:SurfaceHolder?=null;
    //前置镜头获取到的数据展现view
    private fun initCameraSuf(){
        id_surface_camer_view.holder.addCallback(object :SurfaceHolder.Callback{
            override fun surfaceCreated(holder: SurfaceHolder?) {
                mCameraSuf = holder
//                isResetView = true
                initcamera()
//                camera?.setPreviewDisplay(mCameraSuf) //使用getHolder方法把数据返回给surfaceview
            }

            override fun surfaceChanged(
                holder: SurfaceHolder?,
                format: Int,
                width: Int,
                height: Int
            ) {

            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {

            }

        })
    }

    //检查用的权限
    fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            NicePermission(this, object : NicePermissionListener {
                override fun onGranted() {
                    id_surface_camer_view?.postDelayed({
//                        initcamera()
                    }, 1000)
                    initCameraSuf()
                }

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


    }

    override fun setReslut(result: StarMachEntity?) {
        if (result != null) {
            Camerafb = 1
            id_tv_user_nick_name?.text = result.nickname
            id_tv_matchingdegree?.text = "${result.matchingDegree}"
            setStar(result.matchingDegree)
            id_tv_age?.text = "${result.age}"
            id_tv_price?.text = "${result.videoPrice}/min"
            if (!TextUtils.isEmpty(result.video)) {
                ifCharge = true
                playVideo(result.video)
            } else {
                ifCharge = false
            }
            if (TextUtils.equals(result.sex, "2")) {
                id_ll_sex_bg.setBackgroundResource(R.drawable.shape_girl_bg)
            } else {
                id_ll_sex_bg.setBackgroundResource(R.drawable.shape_boy_bg)
            }
            id_img_guoqi?.setLoadImageUrl(result.nationalFlag, false)
            if (!TextUtils.isEmpty(result.headImage)) {
                Glide.with(AppContext.get()).load(result.headImage)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(id_img_user_head)
            }
            val user = SettingPreference.getUserInfoData()
            if (!TextUtils.isEmpty(user.headImage)) {
                Glide.with(this).load(user.headImage)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(id_img_my_head)
            }
        }

    }

    fun setStar(machDegree: Int) {
        when (machDegree) {
            0 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_default)
                id_img_two_star.setImageResource(R.drawable.icon_xing_default)
                id_img_three_star.setImageResource(R.drawable.icon_xing_default)
                id_img_four_star.setImageResource(R.drawable.icon_xing_default)
                id_img_five_star.setImageResource(R.drawable.icon_xing_default)
            }
            20 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_two_star.setImageResource(R.drawable.icon_xing_default)
                id_img_three_star.setImageResource(R.drawable.icon_xing_default)
                id_img_four_star.setImageResource(R.drawable.icon_xing_default)
                id_img_five_star.setImageResource(R.drawable.icon_xing_default)
            }
            40 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_two_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_three_star.setImageResource(R.drawable.icon_xing_default)
                id_img_four_star.setImageResource(R.drawable.icon_xing_default)
                id_img_five_star.setImageResource(R.drawable.icon_xing_default)
            }
            60 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_two_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_three_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_four_star.setImageResource(R.drawable.icon_xing_default)
                id_img_five_star.setImageResource(R.drawable.icon_xing_default)
            }
            80 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_two_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_three_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_four_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_five_star.setImageResource(R.drawable.icon_xing_default)
            }
            100 -> {
                id_img_one_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_two_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_three_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_four_star.setImageResource(R.drawable.icon_xing_liang)
                id_img_five_star.setImageResource(R.drawable.icon_xing_liang)
            }
        }
    }

    fun playVideo(url: String?) {
        id_view_constell_reslut?.visibility = View.VISIBLE
        id_ll_conneting?.visibility = View.GONE

        try {
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer()
            }
            //给MediaPlayer设置播放源
            mediaPlayer?.reset()
            mediaPlayer?.setDataSource(url)
            mediaPlayer?.prepareAsync()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        id_view_constell_reslut?.holder?.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder?) {
                mediaPlayer?.setDisplay(holder)
            }

            override fun surfaceChanged(
                holder: SurfaceHolder?,
                format: Int,
                width: Int,
                height: Int
            ) {
                Log.e("MXL", "surfaceChanged")
            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {
                Log.e("MXL", "surfaceDestroyed")
            }
        })
        mediaPlayer?.setOnCompletionListener {
            Log.e("MXL", "onComplet")
            id_tv_chornometer.stop()
            stopVieo()
            setVideoView()
            mPresenter?.getStarMachReslut()
        }
        mediaPlayer?.setOnPreparedListener {
            Log.e("MXL", "setOnPrep")// 开始播放
            mediaPlayer?.start()
            id_tv_chornometer.start()


        }
    }

    fun setVideoView() {
        id_view_constell_reslut?.visibility = View.GONE
        id_ll_conneting?.visibility = View.VISIBLE
    }

    fun stopVieo() {
        if (mediaPlayer != null) {
            if (mediaPlayer!!.isPlaying) {
                mediaPlayer!!.stop()
            }
        }
    }

    private val runnable: Runnable = object : Runnable {
        override fun run() {
            if (ifCharge == true) {
                mHandler?.postDelayed(this, 60000)
                Log.e("MXL", "每隔一分钟去执行扣费")
                ChatMessageChargeUtils.chatImDEduction(
                    "1",
                    "" + ChatMessageChargeUtils.MESSAGE_CALL_CHAT,
                    object : ChatCallback<String> {
                        override fun onResult(result: String?) {
                            Log.e("MXL", "扣费成功")
                        }

                        override fun onError(code: String?, errorMsg: String?) {
                            Log.e("MXL", "扣费失败")
                            if (!TextUtils.isEmpty(code) && code == "105") {

                            }
                        }

                    })
            }

        }
    }

    /**
     * 初始化摄像头
     */
    fun initcamera() {
        try {
            //如果camera中有值的，则清空camera中的数据
            if (camera != null) {
                camera?.stopPreview()
                camera?.release()
                camera = null
            }
            camera = Camera.open(Camerafb) //开启摄像头,open中需要赋值,0为后置摄像头，1为前置摄像头
            val parameters: Camera.Parameters? = camera?.getParameters() //从摄像头返回的数据
            parameters?.setPreviewFormat(ImageFormat.NV21) //设置摄像头的预览帧格式
            camera?.setDisplayOrientation(90) //调整相机拍到的图像旋转，不然竖着拿手机,图像是横着的
            parameters?.setRotation(90) //调整的图像旋转,不然竖着拿手机,图像是横着的
            //获取尺寸的大小
            val sizeList: List<Camera.Size>? = parameters?.getSupportedPictureSizes()
            if (sizeList?.size!! > 1) {
                val itor: Iterator<Camera.Size> = sizeList.iterator()
                while (itor.hasNext()) {
                    val cur: Camera.Size = itor.next()
                    Log.i("jw", "val$cur")
                }
            }
            //设置图像预览的尺寸
            parameters.setPreviewSize(640, 480)
            parameters.setPictureSize(640, 480)
            camera?.setParameters(parameters) //设置摄像头需要的数据
            if (mCameraSuf!=null){
                camera?.setPreviewDisplay(mCameraSuf) //使用getHolder方法把数据返回给surfaceview
            }
            camera?.setPreviewCallback(this) //摄像头的回调
            camera?.startPreview() //开始预览取景
            mHandler?.post(runnable)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //释放摄像头资源
    fun destroyCamera() {
        if (camera == null) {
            return
        }
        camera!!.setPreviewCallback(null)
        camera!!.stopPreview()
        camera!!.release()
        camera = null
    }

    override fun onStop() {
        super.onStop()
        destroyCamera()
    }

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

    }

    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {

    }
}