package com.all.pdfreader.pro.app.ui.fragment

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.all.pdfreader.pro.app.PRApp
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.FragmentToolsBinding
import com.all.pdfreader.pro.app.model.PdfPickerSource
import com.all.pdfreader.pro.app.ui.act.PdfPickerActivity
import com.all.pdfreader.pro.app.ui.act.PdfResultActivity
import com.all.pdfreader.pro.app.util.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnMediaEditInterceptListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.style.SelectMainStyle
import com.luck.picture.lib.utils.DateUtils
import com.yalantis.ucrop.UCrop
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

class ToolsFrag : BaseFrag() {
    override val TAG: String = "ToolsFrag"
    private lateinit var binding: FragmentToolsBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentToolsBinding.inflate(layoutInflater)
        return binding.root
    }

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

    private fun initView() {
        binding.mergeBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.MERGE)
            startActivity(intent)
        }
        binding.splitBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.SPLIT)
            startActivity(intent)
        }
        binding.lockBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.LOCK)
            startActivity(intent)
        }
        binding.unLockBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.UNLOCK)
            startActivity(intent)
        }
        binding.imgToPdfBtn.setOnClickListener {
            openImagePicker()
        }
        binding.pdfToImgBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.PDF_TO_IMAGES)
            startActivity(intent)
        }
        binding.pdfToLongImgBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.TO_LONG_IMAGE)
            startActivity(intent)
        }
        binding.printBtn.setOnClickListener {
            val intent = PdfPickerActivity.createIntent(requireActivity(), PdfPickerSource.PRINT)
            startActivity(intent)
        }
    }

    private fun openImagePicker() {
        val selectorStyle = PictureSelectorStyle().apply {
            selectMainStyle = SelectMainStyle().apply {
                isSelectNumberStyle = true
                isPreviewSelectNumberStyle = true
                selectBackground = R.drawable.num_checkbox_selector
            }
        }
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(selectorStyle)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setImageSpanCount(3)
            .isGif(false)
            .isFastSlidingSelect(true)
            .setSelectionMode(SelectModeConfig.MULTIPLE)
            .setMaxSelectNum(50)

            .setCompressEngine(object : CompressFileEngine {
                override fun onStartCompress(
                    context: Context?,
                    source: ArrayList<Uri?>?,
                    call: OnKeyValueResultCallbackListener?
                ) {
                    Luban.with(context)
                        .load(source)
                        .ignoreBy(100)
                        .setCompressListener(object : OnNewCompressListener {
                            override fun onStart() {

                            }

                            override fun onSuccess(
                                source: String?,
                                compressFile: File?
                            ) {
                                call?.onCallback(source, compressFile?.absolutePath)
                            }

                            override fun onError(source: String?, e: Throwable?) {
                                call?.onCallback(source, null)
                            }
                        })
                        .launch()
                }
            })
            .setEditMediaInterceptListener(object : OnMediaEditInterceptListener {
                override fun onStartMediaEdit(
                    fragment: Fragment, currentLocalMedia: LocalMedia, requestCode: Int
                ) {
                    val currentEditPath = currentLocalMedia.getAvailablePath()
                    val inputUri = if (PictureMimeType.isContent(currentEditPath)) {
                        currentEditPath.toUri()
                    } else {
                        Uri.fromFile(File(currentEditPath))
                    }
                    val destinationUri = Uri.fromFile(
                        File(
                            getSandboxPath(), DateUtils.getCreateFileName("CROP_") + ".jpeg"
                        )
                    )
                    val uCrop = UCrop.of<Any>(inputUri, destinationUri)
                    val buildOptions = UCrop.Options().apply {
                        isDarkStatusBarBlack(true)
                    }
                    uCrop.withOptions(buildOptions)
                    uCrop.start(requireActivity(), fragment, requestCode)
                }

            }).forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    logDebug("forResult ->${result.size}")
                    if (result.isNotEmpty()) {
                        // result 中可能有带裁剪的 Uri 或原图 Uri
                        // 取出路径列表
                        val paths = result.mapNotNull { media ->
                            media.availablePath
                        }
                        if (paths.isEmpty()) {
                            return
                        }
                        val intent = PdfResultActivity.createIntentInputFile(
                            requireActivity(),
                            ArrayList(paths),
                            PdfPickerSource.IMAGES_TO_PDF
                        )
                        startActivity(intent)
                    }
                }

                override fun onCancel() {
                    logDebug("onCancel")
                }
            })
    }

    fun getSandboxPath(): String {
        val dir = File(PRApp.getContext().externalCacheDir, "SandboxPdfPro")
        if (!dir.exists()) dir.mkdirs()
        return dir.absolutePath
    }
}