package com.ytpm.hydtw.activity

import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import com.ytpm.hydtw.databinding.ActivityWebBinding

class WebActivity : FragmentActivity() {

    private var mTitle: String? = ""
    private var mIndex: Int? = 0
    private lateinit var binding: ActivityWebBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWebBinding.inflate(layoutInflater)
        setContentView(binding.root)

        mTitle = intent.getStringExtra("title")
        mIndex = intent.getIntExtra("index", 0)
        initView()
        initTool()
    }

    private fun initTool() {

        binding.barLL.back.setOnClickListener { finish() }
        binding.barLL.title.text = mTitle
    }

    private fun initView() {

        setupWebView()
        loadHtmlFromAssets()
    }

    private fun setupWebView() {
        binding.webview.settings.javaScriptEnabled = true
        binding.webview.settings.allowFileAccess = true

        binding.webview.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
            }
        }
    }

    private fun loadHtmlFromAssets() {
        // 加载 assets 目录下的 index.html
        when (mIndex) {
            0 -> binding.webview.loadUrl("file:///android_asset/ysxy.html")
            1 -> binding.webview.loadUrl("file:///android_asset/yhxy.html")
        }

        // 如果 HTML 文件在子目录中，使用：
        // webView.loadUrl("file:///android_asset/subdirectory/index.html")
    }

    // 处理返回键，使 WebView 可以后退
    override fun onBackPressed() {
        if (binding.webview.canGoBack()) {
            binding.webview.goBack()
        } else {
            super.onBackPressed()
        }
    }
}