package com.zxhyis.toolss.ui.home

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.zxhyis.toolss.R
import com.zxhyis.toolss.base.TopFragment
import com.zxhyis.toolss.databinding.FragmentViewBinding
import com.zxhyis.toolss.logic.ClickCallBack
import com.zxhyis.toolss.logic.Counts
import com.zxhyis.toolss.logic.FileBean
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.OnItemClickListener
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.setStatusBarTextDark
import com.zxhyis.toolss.logic.showToast
import com.zxhyis.toolss.logic.testLog
import com.zxhyis.toolss.ui.adapter.FileAdapter
import com.zxhyis.toolss.ui.dialog.ExitDialog
import com.zxhyis.toolss.ui.dialog.FIleDialog
import com.zxhyis.toolss.ui.dialog.LoadingDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.sql.Date
import java.text.SimpleDateFormat
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream


@SuppressLint("NotifyDataSetChanged")
class ViewFragment : TopFragment<FragmentViewBinding>() {


    private val dataList = ArrayList<FileBean>()
    private val selectedDataList = ArrayList<FileBean>()
    private lateinit var fileAdapter: FileAdapter
    private var dialog: LoadingDialog? = null
    private var currentPath: String? = null
    private var fileDialog: FIleDialog? = null
    private var exitDialog: ExitDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentViewBinding {
        return FragmentViewBinding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (!Settings.canDrawOverlays(context)) {
//                val intent = Intent(
//                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                    Uri.parse("package:" + requireContext().packageName)
//                )
//                startActivityForResult(intent, 123)
//            }
//        }
    }


    private fun showMenu(v: View) {
        val popupMenu = PopupMenu(requireActivity(), v, 0, 0, R.style.CustomPopupMenu)
        popupMenu.apply {
            menuInflater.inflate(R.menu.select_menu, popupMenu.menu)
            for (i in 0 until menu.size()) {
                val menuItem = menu.getItem(i)
                val spannableString = SpannableString(menuItem.title)
                spannableString.setSpan(
                    ForegroundColorSpan(Color.WHITE),
                    0,
                    spannableString.length,
                    0
                )
                menuItem.title = spannableString
            }
            setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
                when (item.itemId) {
//                    R.id.item_edit -> {
//                        needRefresh = true
//                        mK.inView.ivBack.visibility = View.GONE
//                        mK.inView.tvMenu.visibility = View.GONE
//                        mK.inView.imageSelectAll.visibility = View.VISIBLE
//                        mK.llBottom.visibility = View.GONE
//                        mK.inView.tvTitle.text = getString(R.string.select_project)
//                        fileAdapter.setShow()
//                        return@OnMenuItemClickListener true
//                    }

                    R.id.item_folder -> {
                        fileDialog = FIleDialog()
                        fileDialog?.setCallBack(object : ClickCallBack {
                            override fun clickBack(fileName: String) {
                                val directory = File(currentPath!!)
                                val newFolder = File(directory, fileName)
                                if (!newFolder.exists()) {
                                    newFolder.mkdir()
                                    "Created successfully".showToast()
                                    dataList.add(
                                        FileBean(
                                            newFolder.absolutePath,
                                            newFolder,
                                            newFolder.name,
                                            newFolder.length(),
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                                newFolder.absolutePath
                                            )
                                            else ""
                                        )
                                    )
                                    fileAdapter.notifyDataSetChanged()
                                } else {
                                    "Creation failed".showToast()
                                }
                            }
                        })
                        fileDialog?.showNow(childFragmentManager, "file_create")
                        fileDialog?.isCancelable = true
                        return@OnMenuItemClickListener true
                    }

//                    R.id.item_share -> {
//                        needRefresh = true
//                        mK.inView.icShare.visibility = View.VISIBLE
//                        mK.inView.ivBack.visibility = View.GONE
//                        mK.inView.tvMenu.visibility = View.GONE
//                        mK.inView.imageSelectAll.visibility = View.VISIBLE
//                        mK.inView.tvTitle.text = getString(R.string.select_project)
//                        fileAdapter.setShow()
//                        return@OnMenuItemClickListener true
//                    }
                }
                false
            })
            show()
        }
    }

    @SuppressLint("SuspiciousIndentation", "ServiceCast")
    private fun init() {
        mK.inView.tvTitle.text = getString(R.string.tv_view)
        mK.inView.ivBack.visibility = View.GONE

        mK.inView.icShare.setOnClick(javaClass.simpleName) {

        }

        mK.tvSet.setOnClick(javaClass.simpleName) {
            mK.tvSet.setBackgroundResource(R.drawable.bg_shape_set_click)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {

                Thread {
                    var flag = true
                    while (flag) {
                        flag = !Environment.isExternalStorageManager()
                        Thread.sleep(500)
                        Log.e("MainScope", "flag=$flag")
                    }
                    ActivityUtils.finishAllActivities(false)
                    Log.e("MainScope", "finishAllActivities")
                    //                    ActivityUtils.finishToActivity(MainActivity::class.java, false)
                }.start()

                val uri = Uri.parse("package:${requireContext().packageName}")

                var intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri).apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
//                launchResult(intent) {
//                    toast("返回")
//                }
//                    val dialog = CustomDialog()
//                    dialog.show()
//                        .showManagerStorageDialogSystemIn()
            } else {
                ActivityCompat.requestPermissions(
                    requireActivity(),
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ), Counts.REQUEST_ALL_FILE
                )
            }
        }


        mK.inView.tvMenu.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    showMenu(it)
                } else {
                    "Please apply for permission".showToast()
                }
            } else {
                if (ContextCompat.checkSelfPermission(
                        requireActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    "Please apply for permission".showToast()
                } else {
                    showMenu(it)
                }
            }

        }

        mK.inView.imageSelectAll.setOnClick(javaClass.simpleName) {
            selectedDataList.clear()
            mK.inView.imageSelectAll.isSelected = !mK.inView.imageSelectAll.isSelected
            if (mK.inView.imageSelectAll.isSelected) {
                fileAdapter.setAllSelected()
                for (data in dataList) {
                    selectedDataList.add(data)
                }
            } else {
                fileAdapter.setEmptySelected()
                for (data in dataList) {
                    selectedDataList.remove(data)
                }
            }
        }

    }


    fun viewBack() {
        if (mK.inView.imageSelectAll.visibility == View.VISIBLE) {
            mK.inView.imageSelectAll.visibility = View.GONE
            mK.inView.tvAll.visibility = View.GONE
            mK.inView.tvTitle.visibility = View.GONE
//            mK.inView.icShare.visibility=View.GONE
            fileAdapter.setNoShow()

        } else {
            if (dataList.size > 0) {
                testLog("dataList[0]:${dataList[0].file.parent},big:${Environment.getExternalStorageDirectory().absolutePath}")
                if (dataList[0].file.parent == Environment.getExternalStorageDirectory().absolutePath) {
                    exitDialog = ExitDialog()
                    exitDialog?.showNow(childFragmentManager, "exit_app")
                    exitDialog?.isCancelable = false
                } else {
                    dataList.clear()
                    selectedDataList.clear()
                    val directory = File(currentPath).parentFile
                    val files = directory.listFiles()
                    if (files != null) {
                        for (data in files) {
                            dataList.add(
                                FileBean(
                                    data.absolutePath,
                                    data,
                                    data.name,
                                    data.length(),
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                        data.absolutePath
                                    )
                                    else ""
                                )
                            )
                        }
                        fileAdapter.notifyDataSetChanged()
                        currentPath = directory.absolutePath
                    }
                }
            } else {
                val directory = File(currentPath).parent
                val files = File(directory).listFiles()
                if (files != null) {
                    for (data in files) {
                        testLog(data.absolutePath)
                        dataList.add(
                            FileBean(
                                data.absolutePath,
                                data,
                                data.name,
                                data.length(),
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                    data.absolutePath
                                )
                                else ""
                            )
                        )
                    }
                    fileAdapter.notifyDataSetChanged()
                    currentPath = directory
                    mK.rvAll.visibility = View.VISIBLE
                    mK.icNoFile.visibility = View.GONE
                    mK.tvNoFile.visibility = View.GONE
                }
            }
        }


    }

    private fun initRv() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)
            val currentDir = Environment.getExternalStorageDirectory()
            currentPath = currentDir.absolutePath
            testLog("currentPath:$currentPath")
            val files = currentDir.listFiles()
            if (files != null) {
                for (file in files) {
                    if (!file.isHidden && !file.name.startsWith(".") && file.name != ".face") {
                        testLog(file.name)
                        dataList.add(
                            FileBean(
                                file.absolutePath,
                                file,
                                file.name,
                                file.length(),
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                    file.absolutePath
                                )
                                else ""
                            )
                        )

                    }
                }
            }

            fileAdapter = FileAdapter(dataList, requireActivity(), object : OnItemClickListener {
                override fun onItemClick(file: File) {
                    dataList.clear()
                    if (file.isDirectory) {
                        if (file.listFiles() != null) {
                            if (file.listFiles().isEmpty()) {
                                testLog("files is null")
                                currentPath = file.absolutePath
                                updateEmptyUI()
                            } else {
                                testLog("files not null")
                                for (data in file.listFiles()) {
                                    dataList.add(
                                        FileBean(
                                            data.absolutePath,
                                            data,
                                            data.name,
                                            data.length(),
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                                file.absolutePath
                                            )
                                            else ""
                                        )
                                    )
                                    currentPath = data.parent
                                }
                                fileAdapter.notifyDataSetChanged()
                                updateNextUI()
                            }
                        } else {
                            testLog("files is null")
                            currentPath = file.absolutePath
                            updateEmptyUI()
                        }
                    }
                }
            }, object : Logic {
                override fun doLogic() {
                    remove()
                }

            })
            launch(Dispatchers.Main) {
                if (dataList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(requireActivity())
                    linearLayoutManager.initialPrefetchItemCount = 10
                    mK.rvAll.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = fileAdapter
                        mK.icNoFile.visibility = View.GONE
                        mK.tvNoFile.visibility = View.GONE
                    }

                } else {
                    mK.apply {
                        rvAll.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                    }
                }
                dialog?.dismiss()
            }
        }
    }

    private fun remove() {
        selectedDataList.clear()
        for (selectedData in dataList) {
            if (selectedData.isSelected) {
                selectedDataList.add(selectedData)
            } else {
                selectedDataList.remove(selectedData)
            }
        }
    }

    private fun shareZip() {
//        zipFolder()
//        shareZipFile()
    }

    private fun zipFolder(folderPath: String, zipFilePath: String) {
        val sourceFile = File(folderPath)
        FileOutputStream(zipFilePath).use { fos ->
            ZipOutputStream(BufferedOutputStream(fos)).use { zos ->
                val data = ByteArray(1024)
                val files = sourceFile.listFiles()
                files?.forEach { file ->
                    FileInputStream(file).use { fis ->
                        BufferedInputStream(fis).use { bis ->
                            val zipEntry = ZipEntry(file.name)
                            zos.putNextEntry(zipEntry)
                            var count: Int
                            while (bis.read(data).also { count = it } != -1) {
                                zos.write(data, 0, count)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun updateNextUI() {
        mK.apply {
            tvName.visibility = View.VISIBLE
            rvAll.visibility = View.VISIBLE
            icNoFile.visibility = View.GONE
            tvNoFile.visibility = View.GONE
        }
    }

    private fun updateEmptyUI() {
        mK.apply {
            tvName.visibility = View.GONE
            rvAll.visibility = View.GONE
            icNoFile.visibility = View.VISIBLE
            tvNoFile.visibility = View.VISIBLE
        }
    }

    @SuppressLint("SimpleDateFormat")
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFileCreationTime(filePath: String): String? {
        try {
            val path = Paths.get(filePath)
            val attr = Files.readAttributes(path, BasicFileAttributes::class.java)
            val creationTime = attr.creationTime()
            val date = Date(creationTime.toMillis())
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
            return format.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onResume() {
        super.onResume()
        requireActivity().window.statusBarColor = 0xFFFFFF
        setStatusBarTextDark(requireActivity())
        dataList.clear()
        selectedDataList.clear()
        currentPath = null
//        mK.inView.icShare.visibility=View.GONE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val isShow = Environment.isExternalStorageManager()
            showFileManager(isShow)
        } else {
            val isShow = ContextCompat.checkSelfPermission(
                requireActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
            showFileManager(isShow)
        }

    }

    override fun onPause() {
        super.onPause()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }

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

    fun showFileManager(isShow: Boolean) {

        if (isShow) {
            mK.apply {
                mK.inView.ivBack.visibility = View.GONE
                mK.inView.tvMenu.visibility = View.VISIBLE
                mK.inView.imageSelectAll.visibility = View.GONE
                imagePer.visibility = View.GONE
                tvDes.visibility = View.GONE
                tvSet.visibility = View.GONE
                rvAll.visibility = View.VISIBLE
                tvName.visibility = View.VISIBLE
                dialog = LoadingDialog()
                dialog?.isCancelable = false
                dialog?.showNow(childFragmentManager, "loading")
                initRv()
            }
        } else {
            mK.apply {
                imagePer.visibility = View.VISIBLE
                tvDes.visibility = View.VISIBLE
                tvSet.visibility = View.VISIBLE
                mK.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                rvAll.visibility = View.GONE
                tvName.visibility = View.GONE
            }
        }
    }

}