package com.base.pdfreaderallpdfreader.ui.document

import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdmobHelper
import com.base.pdfreaderallpdfreader.ads.admob.AdmobNativeUtils
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_EXCEL
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PPT
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_WORD
import com.base.pdfreaderallpdfreader.databinding.FragmentDocumentBinding
import com.base.pdfreaderallpdfreader.ui.excel.ExcelActivity
import com.base.pdfreaderallpdfreader.ui.main.DocumentAdapter
import com.base.pdfreaderallpdfreader.ui.main.getAllDocument
import com.base.pdfreaderallpdfreader.ui.main.getExcelDocument
import com.base.pdfreaderallpdfreader.ui.main.getPdfDocument
import com.base.pdfreaderallpdfreader.ui.main.getPptDocument
import com.base.pdfreaderallpdfreader.ui.main.getWordDocument
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.ppt.PptActivity
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentHomeMoreDialog
import com.base.pdfreaderallpdfreader.ui.word.WordActivity
import com.base.pdfreaderallpdfreader.utils.updateMediaStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


class DocumentFragment() : Fragment() {

    private var type = TYPE_PDF

    private lateinit var binding: FragmentDocumentBinding
    private var adapter: DocumentAdapter? = null

    constructor(type: String) : this() {
        this.type = type
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = DocumentAdapter()
        adapter?.itemClickAction = { item: DocumentBean ->
            if (item.type == TYPE_PDF) {
                PdfActivity.jumpPdfActivity(requireActivity(), item)
            } else {
                requireActivity().jumpOtherDocument(item)
            }
        }
        adapter?.moreAction = { item: DocumentBean ->
            if (item.type == TYPE_PDF) {

            } else {
                requireContext().showDocumentHomeMoreDialog(item, this)
            }
        }
        binding.rv.adapter = adapter

        binding.rv.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
//            LogEx.logDebug(TAG, "scrollY=$scrollY oldScrollY=$oldScrollY")

            // 检查当前滚动位置
            val firstVisibleItem: Int =
                (binding.rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()

            if (firstVisibleItem > 3) {
                binding.ivTop.isVisible = true
            }

            if (firstVisibleItem == 0) {
                binding.ivTop.isVisible = false
            }

        }
        binding.ivTop.setOnClickListener {
            binding.rv.scrollToPosition(0)
            binding.ivTop.isVisible = false
        }
        binding.swipeRefreshLayout.setOnRefreshListener {
            initData()
        }
    }

    override fun onResume() {
        super.onResume()
        if (type == TYPE_PDF) {
            if (pdfNeedRefresh) {
                pdfNeedRefresh = false
                initData()
            }
        } else {
            initData()
        }
    }

    private fun initData() {
        binding.swipeRefreshLayout.isRefreshing = true

        lifecycleScope.launch(Dispatchers.IO) {

            requireContext().updateMediaStore()

            val list: List<DocumentBean>
            when (type) {
                TYPE_PDF -> {
                    list = getPdfDocument(requireContext())
                }

                TYPE_WORD -> {
                    list = getWordDocument(requireContext())
                }

                TYPE_EXCEL -> {
                    list = getExcelDocument(requireContext())
                }

                TYPE_PPT -> {
                    list = getPptDocument(requireContext())
                }

                else -> {
                    list = getAllDocument(requireContext())
                }
            }
            launch(Dispatchers.Main) {
                if (list.isEmpty()) {
                    binding.llEmpty.visibility = View.VISIBLE
                    adapter?.submitList(listOf())
                    val flag = AdmobHelper.isShowRvNativeAd()
                    if (flag) {
                        binding.flAd.visibility = View.VISIBLE
                        AdmobNativeUtils.showNativeAd(requireActivity(), binding.flAd, R.layout.layout_admob_document)
                    }
                } else {
                    binding.llEmpty.visibility = View.GONE
                    binding.flAd.visibility = View.GONE
                    adapter?.submitList(getRvAdList(list))
                }
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    private fun getRvAdList(list: List<DocumentBean>): List<DocumentBean> {
        val flag = AdmobHelper.isShowRvNativeAd()
        if (flag) {
            val arrayList = arrayListOf<DocumentBean>()
            arrayList.addAll(list)
            arrayList.add(1, DocumentBean().apply { isAd = true })
            return arrayList
        }
        return list
    }

    fun deleteDocument(item: DocumentBean) {
        val flag = File(item.path).delete()
        if (flag) {
            adapter?.remove(item)
        }
    }

    fun renameDocumentBean(file: File, newName: String) {
        try {
            val newFile = File(file.parentFile, newName)
            val result = file.renameTo(newFile)
            if (result) {
                initData()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        var pdfNeedRefresh: Boolean = true

        fun Activity.jumpOtherDocument(item: DocumentBean) {

            if (item.type == TYPE_WORD) {
                WordActivity.wordDocumentBean = item
                WordActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == TYPE_EXCEL) {
                ExcelActivity.excelDocumentBean = item
                ExcelActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == TYPE_PPT) {
                PptActivity.pptDocumentBean = item
                PptActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
        }
    }
}