package com.zxhy.hfilemanagermaster.duplicate

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ActivityDupPictureBinding
import com.zxhy.hfilemanagermaster.data.DupImageData
import com.zxhy.hfilemanagermaster.knife.dupImage
import com.zxhy.hfilemanagermaster.knife.getDupImageList
import com.zxhy.hfilemanagermaster.permission.alert
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class DupPictureActivity : AppCompatActivity() {
    private lateinit var binding: ActivityDupPictureBinding
    private lateinit var adapter: DupImageAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityDupPictureBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        window.statusBarColor = ContextCompat.getColor(this, R.color.color_C2F300)
        binding.ivArrow.setOnClickListener {
            finish()
        }
        adapter = DupImageAdapter {
            binding.ivAll.isSelected = it
        }
        binding.rv.adapter = adapter
        binding.ivAll.setOnClickListener {
            it.isSelected = adapter.setToggleSelect()
        }
        binding.tvDelete.setOnClickListener {
            val num = adapter.getSelectNum()
            if (num == 0) return@setOnClickListener
            this.alert("当前选中${num}项,是否确认删除", "删除确认") {
                positiveButton("确定") { dialog ->
                    dialog.dismiss()
                }
                negativeButton("取消") { dialog ->
                    dialog.dismiss()
                }
                //禁止取消
                isCancel(false)
            }
        }


        loadData()
    }

    private fun loadData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val list = dupImage()
            val dupDataList = arrayListOf<DupImageData>()
            val dupList = getDupImageList(list)
            dupList.forEach {
                dupDataList.add(DupImageData(dupList = it))
            }
            lifecycleScope.launch(Dispatchers.Main) {
                adapter.setData(dupDataList)
            }
        }
    }
}