package com.zxhyis.tools.ui.`fun`


import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.zxhyis.tools.R
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityPictureBinding
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.ImageInfoBean
import com.zxhyis.tools.logic.Logic
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.shareMultipleImages
import com.zxhyis.tools.logic.showToast
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.ui.adapter.ImageAdapter
import com.zxhyis.tools.ui.dialog.LoadingDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

@SuppressLint("NotifyDataSetChanged")
class PictureActivity : TopActivity<ActivityPictureBinding>() {

    private val imageList = ArrayList<ImageInfoBean>()
    private val imageSelectedList = ArrayList<ImageInfoBean>()
    private lateinit var imageAdapter: ImageAdapter
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var dialog: LoadingDialog? = null
    private var needRefresh=false

    override fun getViewBinding1(): ActivityPictureBinding {
        return ActivityPictureBinding.inflate(layoutInflater)
    }


    @SuppressLint("Recycle")
    override fun init() {
        vb.inPicture.tvTitle.text = getString(R.string.tv_picture)

        vb.inPicture.ivBack.setOnClick {
            finish()
        }

        vb.tvSet.setOnClick {
            vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set_click)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                result.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ), Counts.REQUEST_ALL_FILE
                )
            }
        }

        vb.inPicture.tvMenu.setOnClick {
            needRefresh=true
            if (imageList.size > 0) {
                vb.inPicture.ivBack.visibility = View.GONE
                vb.inPicture.tvMenu.visibility = View.GONE
                vb.inPicture.imageSelectAll.visibility = View.VISIBLE
                vb.inPicture.tvAll.visibility = View.VISIBLE
                vb.llBottom.visibility = View.VISIBLE
                vb.inPicture.tvTitle.text = getString(R.string.select_project)
                imageAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }

        vb.inPicture.imageSelectAll.setOnClick {
            imageSelectedList.clear()
            vb.inPicture.imageSelectAll.isSelected = !vb.inPicture.imageSelectAll.isSelected
            if (vb.inPicture.imageSelectAll.isSelected) {
                imageAdapter.selectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
            } else {
                imageAdapter.deselectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share)
                vb.ivDelete.setImageResource(R.drawable.ic_delete)
            }
        }

        vb.ivShare.setOnClick {
            when {
                imageSelectedList.size in 1..3 -> {
                   shareImages()
                }

                imageSelectedList.size > 3 -> {
                    "Select up to three".showToast()
                }

                else -> {
                    "Select at least one".showToast()
                }
            }
        }

        vb.ivDelete.setOnClick {
            if (imageSelectedList.size > 0) {
                deleteImages()
                vb.apply {
                    inPicture.clInclude.visibility = View.GONE
                    rvImage.visibility = View.GONE
                    icNoFile.visibility = View.GONE
                    tvNoFile.visibility = View.GONE
                    imageLoad.visibility = View.VISIBLE
                    llBottom.visibility=View.GONE
                    imageLoad.playAnimation()
                    tvLoad.visibility = View.VISIBLE
                }
            } else {
                "Select at least one".showToast()
            }
        }

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })
    }


    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        imageList.clear()
        imageSelectedList.clear()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvImage.visibility = View.VISIBLE
                    loadImages()
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvImage.visibility = View.GONE
                }
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvImage.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvImage.visibility = View.VISIBLE
                    loadImages()
                }
            }
        }
    }

    @SuppressLint("Recycle", "CutPasteId")
    private fun loadImages() {//加载图片
        dialog = LoadingDialog()
        dialog?.isCancelable = false
        dialog?.showNow(supportFragmentManager, "loading")

        CoroutineScope(Dispatchers.IO).launch {
            delay(1000)
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                null
            )
            cursor?.let {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                while (cursor.moveToNext()) {
                    val imagePath = cursor.getString(columnIndex)
                    val bitmap = BitmapFactory.decodeFile(imagePath)
                    val file = File(imagePath)
                    imageList.add(ImageInfoBean(imagePath, bitmap, file, Uri.parse(imagePath),needRefresh))//数据源
                }
                cursor.close()
                dialog?.dismiss()

                imageAdapter = ImageAdapter(
                    imageList,
                    this@PictureActivity,
                    object : Logic {
                        override fun doLogic() {
                            remove()
                            if (imageSelectedList.size > 0) {
                                vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                                vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
                            } else {
                                vb.ivShare.setImageResource(R.drawable.ic_share)
                                vb.ivDelete.setImageResource(R.drawable.ic_delete)
                            }
                        }

                    }
                )


            }
            //init rv
            launch(Dispatchers.Main) {
                if (imageList.size > 0) {
                    val gridLayoutManager = GridLayoutManager(this@PictureActivity, 3)
                    gridLayoutManager.initialPrefetchItemCount = 10
                    vb.rvImage.apply {
                        layoutManager = gridLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = imageAdapter
                    }
                    vb.apply {
                        rvImage.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                    }
                } else {
                    vb.apply {
                        rvImage.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                    }
                }
            }

        }

    }

    private fun remove() {
        imageSelectedList.clear()
        for (image in imageList) {
            if (image.isSelected) {
                imageSelectedList.add(image)
            } else {
                imageSelectedList.remove(image)
            }
        }
    }

    private fun shareImages() {
        val uriList = ArrayList<Uri>()
        for (image in imageSelectedList) {
            uriList.add(image.imageUri)
        }
        shareMultipleImages(uriList,this)
    }

    private fun deleteImages() {
        deleteImagesWhenDone(imageSelectedList) {
            startActivity<ResultActivity>("from" to "picture")
            finish()
        }
    }

    private fun deleteImagesWhenDone(list: ArrayList<ImageInfoBean>, onAllDeleted: () -> Unit) {
//        for (image in list) {
//            image.file.delete()
//            if (image.file.delete()) {
//                deletedCount++
//                if (deletedCount == total) {
//                    onAllDeleted()
//                }
//            }
//        }
        for ((index, number) in list.withIndex()) {
            number.file.delete()
            if (index == list.lastIndex) {
                onAllDeleted()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        imageList.clear()
        imageSelectedList.clear()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }


}