package com.cherry.lib.doc.widget

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.ContextWrapper
import android.os.AsyncTask
import android.text.Html
import android.text.SpannableString
import android.text.TextUtils
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.cherry.lib.doc.util.WordConverter
import org.apache.commons.io.FileUtils
import java.io.File

class PoiViewer(private var mContext: Context) {
    private val TAG = "PoiViewer"
    private var mFilePath: String = ""
    private var mFileExt: String = ""
    private var mFileCachePath: String = ""
    private var mProgressDialog: ProgressDialog? = null
    private lateinit var mRootView: ViewGroup
    private lateinit var mWebView: WebView

    init {
        initView()
        initCacheDir()
    }

    var singleTapAction: (() -> Unit)? = null

    @SuppressLint("SetJavaScriptEnabled", "ClickableViewAccessibility")
    private fun initView() {
        mProgressDialog = ProgressDialog(mContext)
        mProgressDialog?.setMessage("loading...")
        // 初始化网页
        mWebView = WebView(mContext)
        mWebView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        mWebView.getSettings().javaScriptEnabled = true
        mWebView.getSettings().domStorageEnabled = true
        mWebView.getSettings().allowFileAccess = true
        mWebView.getSettings().allowFileAccessFromFileURLs = true
        mWebView.getSettings().allowUniversalAccessFromFileURLs = true
        mWebView.getSettings().cacheMode = WebSettings.LOAD_NO_CACHE
        mWebView.getSettings().setSupportZoom(true)
        mWebView.getSettings().builtInZoomControls = true
        mWebView.getSettings().displayZoomControls = false
        mWebView.getSettings().useWideViewPort = true
        mWebView.getSettings().loadWithOverviewMode = true
        mWebView.getSettings().textZoom = 128
        mWebView.getSettings().layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN

        val lister = MyOnTouchLister()
        lister.singleTapAction = {
            singleTapAction?.invoke()
        }
        mWebView.setOnTouchListener(lister)
    }

    private fun initCacheDir() {
        mFileCachePath = mContext.cacheDir.absolutePath + "/poiCache/"
        val file = File(mFileCachePath)
        if (!file.exists()) {
            file.mkdir()
        }
    }

    fun loadFile(fileLayout: ViewGroup, filePath: String) {
        mRootView = fileLayout
        mFilePath = filePath
        mFileExt = filePath.substring(filePath.lastIndexOf("."))
        mProgressDialog?.show()
        ConvertTask().execute(filePath)
    }

    @SuppressLint("StaticFieldLeak")
    inner class ConvertTask : AsyncTask<String?, Void?, String?>() {
        @Deprecated("Deprecated in Java")
        override fun doInBackground(vararg params: String?): String? {
            val filePath = params[0] ?: ""
            if (mFileExt.equals(".doc", ignoreCase = true) || mFileExt.equals(".docx", ignoreCase = true)) {
                val wordConverter = WordConverter(filePath, mFileCachePath)
                return wordConverter.returnPath
            }
            //            if (mFileExt.equalsIgnoreCase(".xls") || mFileExt.equalsIgnoreCase(".xlsx")) {
//                ExcelConverter excelConverter = new ExcelConverter(filePath, mFileCachePath);
//                excelConverter.readExcelToHtml();
//                return excelConverter.mUrlPath;
//            }
            return if (mFileExt.equals(".txt", ignoreCase = true)) {
                try {
                    val txtString = FileUtils.readFileToString(File(filePath), "UTF-8")
                    val spanString = SpannableString(txtString)
                    val htmlString = Html.toHtml(spanString)
                    val fileName = filePath.substring(filePath.lastIndexOf("/") + 1)
                    val fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
                    val htmlName = fileName.replace(fileExt, "html")
                    val tempFile = File(mFileCachePath, htmlName)
                    FileUtils.writeStringToFile(tempFile, htmlString, "UTF-8")
                    "file:///" + tempFile.absolutePath
                } catch (e: Exception) {
                    null
                }
            } else null
        }


        override fun onPostExecute(returnString: String?) {
            mProgressDialog!!.dismiss()
            if (TextUtils.isEmpty(returnString)) {
                Toast.makeText(mContext, "open failed", Toast.LENGTH_SHORT).show()
                scanForActivity(mContext)!!.finish()
                return
            }
            mWebView.loadUrl(returnString!!)
            mRootView.addView(mWebView)
        }
    }

    fun recycle() {
        mWebView.removeAllViews()
    }

    fun scanForActivity(context: Context?): AppCompatActivity? {
        if (context == null) return null
        if (context is AppCompatActivity) {
            return context
        } else if (context is ContextWrapper) {
            return scanForActivity(context.baseContext)
        }
        return null
    }
}
