package com.base.pdfreaderallpdfreader.ui.view

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.text.method.PasswordTransformationMethod
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.content.FileProvider
import androidx.core.widget.addTextChangedListener
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.bean.ConstObject
import com.base.pdfreaderallpdfreader.databinding.DialogPageNumberBinding
import com.base.pdfreaderallpdfreader.databinding.DialogPdfMoreBinding
import com.base.pdfreaderallpdfreader.ui.main.saveBookmarkChange
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity.Companion.jumpMerge
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity.Companion.jumpSplit
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentDetail
import com.base.pdfreaderallpdfreader.utils.IntentShareUtils
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.NumberRangeFilter
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.checkStorePermission
import com.base.pdfreaderallpdfreader.utils.SpStringUtils
import com.base.pdfreaderallpdfreader.utils.SpStringUtils.BOOKMARK_KEY
import com.base.pdfreaderallpdfreader.utils.ToastUtils.toast
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.File

object PdfDialog {

//    //pdf首页弹窗
//    @SuppressLint("NotifyDataSetChanged")
//    fun Context.showPdfHomeMoreDialog(
//        item: DocumentBean,
//        mainActivity: MainActivity,
//        documentFragment: DocumentFragment,
//        documentPageFragment: DocumentPageFragment,
//    ): BottomSheetDialog {
//        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
//        val binding = DialogPdfHomeMoreBinding.inflate(LayoutInflater.from(this))
//        dialog.setContentView(binding.root)
//        dialog.setCanceledOnTouchOutside(false)
//
//        dialog.show()
//
//        val parentView = binding.root.parent as View
//        val behavior = BottomSheetBehavior.from(parentView)
//        //展开
//        behavior.state = BottomSheetBehavior.STATE_EXPANDED
//
//        val file = File(item.path)
//        binding.tvName.text = file.name
//        binding.tvInfo.text = file.lastModified().toFormatTime() + " " + file.length().toFormatSize()
//        if (item.isBookmarked) {
//            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
//        } else {
//            binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
//        }
//        binding.ivBookmark.setOnClickListener {
//            item.isBookmarked = !item.isBookmarked
//            if (item.isBookmarked) {
//                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_s)
//            } else {
//                binding.ivBookmark.setImageResource(R.mipmap.h_soucang_n)
//            }
//            mainActivity.mainPresenter.changeBookmark(item.path, item.isBookmarked, documentPageFragment)
//
//        }
//        binding.llRename.setOnClickListener {
//            showDocumentRenameDialog(file.name, okAction = { newName ->
//                dialog.dismiss()
//                mainActivity.mainPresenter.renameDocumentBean(file, newName, documentPageFragment)
//            })
//        }
//        binding.llSplit.setOnClickListener {
//            dialog.dismiss()
//            if (item.state == 1) {
//                showPdfPwdDialog(
//                    state = item.state, path = item.path, firstDialog = dialog, isCheckPwd = true, verificationAction = {
//                        documentPageFragment.splitPdf(item.path, it)
//                    })
//            } else {
//                documentPageFragment.splitPdf(item.path)
//            }
//        }
//        binding.llMerge.setOnClickListener {
//            dialog.dismiss()
//            documentPageFragment.mergePdf(item.path)
//        }
//        binding.llDelete.setOnClickListener {
//            dialog.dismiss()
//            showDeleteDialog {
//                mainActivity.mainPresenter.deleteDocument(item.path, documentPageFragment)
//                documentFragment.searchDeleteDocument(item)
//            }
//        }
//        binding.llDetail.setOnClickListener {
//            showDocumentDetail(item.path)
//        }
//        binding.llShare.setOnClickListener {
//            val intent = IntentShareUtils.sharePdfIntent(item.uri)
//            runCatching {
//                startActivity(intent)
//            }
//        }
//        if (item.state == 1) {
//            binding.tvLock.text = getString(R.string.unlock_pdf)
//        }
//        if (item.state == 0) {
//            binding.tvLock.text = getString(R.string.lock_pdf)
//        }
//        binding.llLock.setOnClickListener {
//            showPdfPwdDialog(state = item.state, path = item.path,
//                firstDialog = dialog,
//                isCheckPwd = false,
//                encryptionAction = {
//                    dialog.dismiss()
//                    mainActivity.mainPresenter.changePdfLock(item, documentPageFragment)
//                })
//        }
//        dialog.setOnDismissListener {
//        }
//        return dialog
//    }

    fun Activity.showPdfMoreDialog(
        pdfActivity: PdfActivity,
        pageNumber: Int,
        pafPath: String,
        uri: String? = null,
        pwd: String? = null,
    ) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPdfMoreBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.llJump.setOnClickListener {
            showJumpPageNumberDialog(pageNumber) { pageIndex ->
                dialog.dismiss()
                pdfActivity.jumpPage(pageIndex)
            }
        }
        binding.llMerge.setOnClickListener {
            dialog.dismiss()
            jumpMerge(pdfActivity)

        }
        binding.llSplit.setOnClickListener {
            dialog.dismiss()
            jumpSplit(pdfActivity, pafPath, uri, pwd)
        }
        binding.llDetail.setOnClickListener {
            showDocumentDetail(pafPath)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        var isBookmarked = bookmarkList.contains(pafPath)
        if (isBookmarked) {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
        } else {
            binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
        }
        binding.ivBookmark.setOnClickListener {
            isBookmarked = !isBookmarked
            if (isBookmarked) {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_s)
            } else {
                binding.ivBookmark.setImageResource(R.mipmap.pdf_bookmark_n)
            }
            saveBookmarkChange(isBookmarked, pafPath)
        }
        binding.llShare.setOnClickListener {
            dialog.dismiss()
            runCatching {
                val pkg = this.packageName
                LogEx.logDebug("showPdfMoreDialog", "pkg=$pkg")
                val uri = FileProvider.getUriForFile(
                    this, this.packageName + ".provider", File(pafPath)
                )
                startActivity(Intent.createChooser(IntentShareUtils.sharePdfIntent(uri), "Share PDF"))
            }
        }

    }

//    @SuppressLint("SetTextI18n")
//    fun Context.showPdfPwdDialog(
//        state: Int,
//        path: String = "",
//        uri: String? = null,
//        firstDialog: Dialog? = null,
//        isCheckPwd: Boolean = false,
//        verificationAction: ((pwd: String) -> Unit)? = null,
//        encryptionAction: (() -> Unit)? = null,
//        cancelAction: (() -> Unit)? = null,
//    ) {
//        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
//        val binding = DialogPdfPasswordBinding.inflate(LayoutInflater.from(this))
//        dialog.setContentView(binding.root)
//        dialog.setCanceledOnTouchOutside(false)
//
//        val window = dialog.window
//        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
//
//        dialog.show()
//
//        val parentView = binding.root.parent as View
//        val behavior = BottomSheetBehavior.from(parentView)
//        //展开
//        behavior.state = BottomSheetBehavior.STATE_EXPANDED
//
//        if (!isCheckPwd) {
//            if (state == 1) {
//                binding.tvTittle.text = getString(R.string.delete_password)
//                binding.tvTip.text = getString(R.string.delete_password_the_file_is_not_password_protected)
//            }
//            if (state == 0) {
//                binding.tvTittle.text = getString(R.string.set_password)
//                binding.tvTip.text = getString(R.string.set_password_protection_pdf)
//
//            }
//        } else {
//            binding.tvTittle.text = getString(R.string.input_password)
//            val file = File(path)
//            binding.tvTip.text = getString(R.string.password_protected, file.name)
//            binding.tvInputTip.visibility = View.VISIBLE
//        }
//
//        binding.edit.requestFocus()
//        binding.edit.addTextChangedListener {
//            binding.tvConfirm.isEnabled = it.toString().isNotEmpty()
//            binding.tvErrorTip.visibility = View.GONE
//        }
//
//        binding.tvCancel.setOnClickListener {
//            dialog.dismiss()
//            cancelAction?.invoke()
//        }
//        binding.tvConfirm.setOnClickListener {
//
//            val pwd = binding.edit.text.toString()
//
//            if (!isCheckPwd) {
//
//                //加锁逻辑
//                if (state == 0) {
//                    PdfBoxUtils.setPassword(path, pwd, pwd)
//                    toast("Success Encryption")
//                    encryptionAction?.invoke()
//                    dialog.dismiss()
//                    firstDialog?.dismiss()
//                }
//                //解锁逻辑
//                if (state == 1) {
//                    val result = PdfBoxUtils.checkPwd(path, pwd, uri)
//                    LogEx.logDebug("checkPwd", "result=$result")
//                    if (result) {
//                        PdfBoxUtils.clearPassword(path, pwd)
//                        toast("clear Encryption")
//                        encryptionAction?.invoke()
//                        dialog.dismiss()
//                        firstDialog?.dismiss()
//                    } else {
//                        binding.tvErrorTip.visibility = View.VISIBLE
//                    }
//                }
//            } else {
//                //验证密码逻辑
//                val result = PdfBoxUtils.checkPwd(path, pwd, uri)
//                if (!result) {
//                    binding.tvErrorTip.visibility = View.VISIBLE
//                    return@setOnClickListener
//                }
//                dialog.dismiss()
//                firstDialog?.dismiss()
//                verificationAction?.invoke(pwd)
//            }
//
//        }
//        binding.ivEye.setOnClickListener {
//
//            if (binding.edit.transformationMethod == null) {
//                // 隐藏密码
//                binding.edit.transformationMethod = PasswordTransformationMethod()
//                binding.ivEye.setImageResource(R.mipmap.weishuru)
//            } else {
//                // 显示密码
//                binding.edit.transformationMethod = null
//                binding.ivEye.setImageResource(R.mipmap.yishuru)
//            }
//        }
//
//    }


    fun Context.showJumpPageNumberDialog(pageNumber: Int, okAction: ((pageIndex: Int) -> Unit)?) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogPageNumberBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        val window = dialog.window
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.edit.filters = arrayOf(NumberRangeFilter(1, pageNumber + 1))
        binding.edit.hint = "1 - ${pageNumber + 1}"
        binding.edit.addTextChangedListener {
            binding.tvOk.isEnabled = !it.isNullOrEmpty()
        }
        binding.edit.requestFocus()
        binding.tvOk.setOnClickListener {
            val number = binding.edit.text.toString()
            if (number.isEmpty()) {
                toast("number can't be empty!")
                return@setOnClickListener
            }
            dialog.dismiss()
            okAction?.invoke(number.toInt() - 1)
        }
    }
}