package com.sketch.art.trace.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.sketch.art.trace.R
import com.sketch.art.trace.adapter.AdapterUpload
import com.sketch.art.trace.databinding.ActivityUploadLayoutBinding
import com.sketch.art.trace.dialog.DialogSelect
import com.sketch.art.trace.listener.OnDialogClickListener
import com.sketch.art.trace.mydata.BeanUpload
import com.sketch.art.trace.mydata.MyDataBase
import com.sketch.art.trace.tools.App
import com.sketch.art.trace.tools.ComManager
import com.sketch.art.trace.tools.ItemDec
import java.io.File


class UploadActivity : AppCompatActivity() {

    private lateinit var binding: ActivityUploadLayoutBinding

    private lateinit var cameraLauncher: ActivityResultLauncher<Uri>
    private lateinit var cameraPermissionLauncher: ActivityResultLauncher<String>
    private var photoUri: Uri? = null


    private lateinit var permissions: Array<String>
    private var dialog: DialogSelect? = null
    private lateinit var adapterUpload: AdapterUpload
    private lateinit var galleryLauncher: ActivityResultLauncher<Intent>
    private var storePermissionsLauncher: ActivityResultLauncher<Array<String>>? = null


    private lateinit var cameraFile: File
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUploadLayoutBinding.inflate(layoutInflater)
        ComManager.setStatusBarTextColor(this, true)
        setContentView(binding.root)
        onInit()
        initClick()

    }


    private fun initClick() {
        binding.back.setOnClickListener {
            finish()
        }
        binding.addImg.setOnClickListener {
            dialog = dialog ?: DialogSelect(object :
                OnDialogClickListener {
                override fun onClickCamera() {
                    openCameraWithPermission()
                }

                override fun onClickGallery() {
                    openGalleryWithPermission()
                }

            })
            dialog!!.show(supportFragmentManager, "")
        }
    }

    private fun onInit() {
        binding.loading.visibility = View.VISIBLE
        loadData()

        cameraPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
                if (granted) {
                    takePhoto()
                } else {
                    Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
                }
            }
        cameraLauncher =
            registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
                if (success && photoUri != null) {
                    saveUploadImage(photoUri!!, true)
                }
            }
        storePermissionsLauncher = registerForActivityResult<Array<String>, Map<String, Boolean>>(
            ActivityResultContracts.RequestMultiplePermissions()

        ) {
            var isGranted = true
            for ((string, value) in it) {
                if (!value) {
                    isGranted = false
                }

            }
            if (isGranted) {
                takeGallery()
            } else {
                Toast.makeText(this@UploadActivity, " Permission denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }
        galleryLauncher = registerForActivityResult<Intent, ActivityResult>(
            ActivityResultContracts.StartActivityForResult()
        ) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK && result.data != null) {
                val imageUri = result.data!!.data
                imageUri?.let { saveUploadImage(it) }
            }
        }
    }

    private fun loadData() {
        adapterUpload =
            AdapterUpload(this@UploadActivity) {
                updateUi(adapterUpload.itemCount > 0)
            }
        Thread {
            val importUrises = MyDataBase.queryAllImport()
            runOnUiThread {
                adapterUpload.setData(importUrises)
                updateUi(importUrises.size > 0)
                binding.loading.visibility = View.GONE
            }
        }.start()
        binding.recyclerview.run {
            val itemDec = ItemDec(10, 10, 5)
            addItemDecoration(itemDec)
            adapter = adapterUpload
            layoutManager = GridLayoutManager(this@UploadActivity, 3)
        }

    }


    private fun updateUi(isShow: Boolean) {
        if (isShow) {
            binding.recyclerview.visibility = View.VISIBLE
            binding.layoutNoImport.visibility = View.GONE
        } else {
            binding.recyclerview.visibility = View.GONE
            binding.layoutNoImport.visibility = View.VISIBLE
        }
    }


    private fun openGalleryWithPermission() {
        permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
        if (!ComManager.checkPermission(this, permissions)) {
            storePermissionsLauncher!!.launch(permissions)
        } else {
            takeGallery()
        }
    }

    private fun takeGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.type = "image/*"
        galleryLauncher.launch(intent)
    }

    private fun openCameraWithPermission() {
        val permission = Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(
                this,
                permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            cameraPermissionLauncher.launch(permission)
        } else {
            takePhoto()
        }
    }

    private fun takePhoto() {
        Log.d(App.TAG, "------takePhoto")
        cameraFile = File.createTempFile("IMG_", ".jpg", cacheDir)
        photoUri = FileProvider.getUriForFile(this, "${packageName}.fileprovider", cameraFile)
        cameraLauncher.launch(photoUri)

    }


    private fun saveUploadImage(imageUri: Uri, isCamera: Boolean = false) {
        var targetFile: File? = null
        var targetFilePath: String? = null
        binding.loading.visibility = View.VISIBLE
        val uriFileSize = ComManager.getUriFileSize(this@UploadActivity, imageUri)
        Log.d(App.TAG, "------uriFileSize-----$uriFileSize--Mb  imageUri=${imageUri}")
        if (uriFileSize >= 5) {
            binding.loading.visibility = View.GONE
            Toast.makeText(
                this@UploadActivity,
                getString(R.string.import_im_too_big),
                Toast.LENGTH_SHORT
            ).show()
            return
        }

        if (isCamera) {
            if (cameraFile.exists()) {
                targetFile = cameraFile
                targetFilePath = cameraFile.absolutePath
            }
        } else {
            //相册导入的照片，构建同名文件放在files目录下，并且复制图片到这个目录下
            val lastPathSegment: String = imageUri.lastPathSegment!!
            val index = lastPathSegment.lastIndexOf("/")
            val name = lastPathSegment.substring(index + 1)
            targetFilePath = ComManager.getImportPath(name)
            targetFile = targetFilePath?.let { File(it) }

        }
        Log.d(
            App.TAG,
            "------targetFilePath-----$targetFilePath-- targetFile.name=${targetFile?.name}"
        )
        val isimport = MyDataBase.queryIsImport(targetFilePath)
        Thread {
            if (targetFile!!.exists()) {
                if (!isimport) {
                    MyDataBase.insertImport(targetFilePath)
                }
                runOnUiThread(Runnable {
                    binding.loading.visibility = View.GONE
                    if (isimport) {
                        Toast.makeText(
                            this@UploadActivity,
                            getString(R.string.import_already),
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        val beanUpload = BeanUpload()
                        beanUpload.uri = targetFilePath
                        adapterUpload.addData(beanUpload)
                        updateUi(true)
                    }
                })
            } else {
                Log.d(App.TAG, "---------------------else   targetFile.name=${targetFile.name}")
                //复制图片到files目录下
                val b = ComManager.saveToInternalStorage(
                    targetFile.name,
                    imageUri,
                    this@UploadActivity
                )
                if (b) {
                    MyDataBase.insertImport(targetFilePath)
                }
                runOnUiThread {
                    binding.loading.visibility = View.GONE
                    if (b) {
                        val beanUpload = BeanUpload()
                        beanUpload.uri = targetFilePath
                        adapterUpload.addData(beanUpload)
                        updateUi(true)
                    } else {
                        Toast.makeText(
                            this,
                            getString(R.string.import_fail),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        }.start()
    }
}