package com.example.base.dialog

import android.app.AlertDialog
import android.app.Dialog
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.DialogFragment
import com.example.base.R
import com.example.base.extensions.toGrantUri
import com.example.base.utils.Utils
import java.io.File
import java.util.UUID

/**
 * time: 2021/08/11
 * desc: 调用拍照选择单一图片
 */
class SelectPhotoDialogFragment : DialogFragment() {

    private var mOnBackListener: ((uri: Uri) -> Unit)? = null     //回调事件

    private val isCrop by lazy { arguments?.getBoolean(ARG_IS_CROP) ?: false }

    // 拍照用的uri
    private var cameraUri: Uri? = null

    private val ratio by lazy { arguments?.getString(CORP_RATIO) ?: "" }

    init {
        val file = File(Utils.getApp().externalCacheDir, "${UUID.randomUUID()}.jpg")
        cameraUri = file.toGrantUri()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val view = View.inflate(requireContext(), R.layout.mvvm_dialog_select_photo, null)
        val dialog = AlertDialog.Builder(requireContext())
        dialog.setView(view)

        // 拍照
        view.findViewById<TextView>(R.id.tvCamera).setOnClickListener {
            takePicture.launch(cameraUri)
        }
        // 相册
        view.findViewById<TextView>(R.id.tvGallery).setOnClickListener {
            getContent.launch("image/*")
        }

        return dialog.create()
    }

    // 拍照
    private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) {
        if (it) {
            if (isCrop) {
                if (ratio.isNotEmpty()) {
                    val aspectX = ratio.split("-")[0].toInt()
                    val aspectY = ratio.split("-")[1].toInt()
                    cropImageContent.launch(CropImageResult(cameraUri!!, aspectX = aspectX, aspectY = aspectY))
                } else {
                    cropImageContent.launch(CropImageResult(cameraUri!!))
                }

            } else {
                mOnBackListener?.invoke(cameraUri!!)
                dismiss()
            }
        }
    }

    // 相册
    private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) {
        if (it != null) {
            if (isCrop) {
                if (ratio.isNotEmpty()) {
                    val aspectX = ratio.split("-")[0].toInt()
                    val aspectY = ratio.split("-")[1].toInt()
                    cropImageContent.launch(CropImageResult(it, aspectX = aspectX, aspectY = aspectY))
                } else {
                    cropImageContent.launch(CropImageResult(it))
                }
            } else {
                mOnBackListener?.invoke(it)
                dismiss()
            }
        }

    }

    // 裁剪
    private val cropImageContent = registerForActivityResult(CropImageContract()) {
        it?.let {
            mOnBackListener?.invoke(it)
            dismiss()
        }
    }

    // 成功回调
    fun setOnSelectListener(listener: ((uri: Uri) -> Unit)) {
        mOnBackListener = listener
    }

    companion object {
        private const val ARG_IS_CROP = "arg_is_crop"
        private const val CORP_RATIO = "ratio"
        fun newInstance(isCrop: Boolean = false, format: String? = null): SelectPhotoDialogFragment {
            val arg = Bundle()
            arg.putBoolean(ARG_IS_CROP, isCrop)
            arg.putString(CORP_RATIO, format)
            val fragment = SelectPhotoDialogFragment()
            fragment.arguments = arg
            return fragment
        }
    }
}