package com.gh.gamecenter.setting.compose.activity

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.os.Environment
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ScrollView
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.DeviceUtils
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.copyTextAndToast
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.core.provider.IDirectProvider
import com.gh.gamecenter.setting.compose.R
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*

class NetworkDiagnosisActivity : ToolBarActivity() {

    class ProgressAndDetail(val progress: Int, val detail: String)

    private lateinit var mResult: TextView
    private lateinit var mProgress: TextView
    private lateinit var mWebView: WebView
    private lateinit var mScrollView: ScrollView
    private lateinit var mSuggestBtn: TextView

    private val builder = SpannableStringBuilder()

    private val mSuccessHint = "诊断完毕。（ 点击复制 ）\n"

    private var mProgressData = 0


    override fun getLayoutId(): Int {
        return R.layout.activity_network_diagnosis
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mResult = findViewById(R.id.network_diagnosis_result)
        mProgress = findViewById(R.id.network_diagnosis_progress)
        mWebView = findViewById(R.id.network_diagnosis_web)
        mScrollView = findViewById(R.id.network_diagnosis_scrollview)
        mSuggestBtn = findViewById(R.id.network_diagnosis_suggest)

        setNavigationTitle("网络诊断")
        // 5.0后，Android对WebView做了优化，此为关闭该优化
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            WebView.enableSlowWholeDocumentDraw()
        }

        Observable.create(ObservableOnSubscribe<ProgressAndDetail> {

            var progress = 0

            // 1.获取当前网络情况，network/ip/mac/sim

            // Network 2G/3G/4G/WIFI
            builder.append("Network:")
            builder.append(DeviceUtils.getNetwork(applicationContext))
            builder.append("\n")

            progress += 3
            it.onNext(ProgressAndDetail(progress, builder.toString()))

            // IP
            builder.append("IP:")
            builder.append(DeviceUtils.getIPAddress(applicationContext))
            builder.append("\n")

            progress += 3
            it.onNext(ProgressAndDetail(progress, builder.toString()))

            // MAC
            builder.append("MAC:")
            builder.append("")
            builder.append("\n")

            progress += 3
            it.onNext(ProgressAndDetail(progress, builder.toString()))

            // SIM
            builder.append("SIM:")
            builder.append("")
            builder.append("\n")

            progress += 3
            it.onNext(ProgressAndDetail(progress, builder.toString()))

            builder.append("-----------------------------------------------------------------------\n")

            // 2.ping域名
            val domains = arrayOf(
                "api.ghzs.com",
                "download.ghzs.com",
                "apk.ghzs666.com",
                "image.ghzs666.com",
                "image.ghzhushou.com"
            )
            for (domain in domains) {
                builder.append(DeviceUtils.ping(domain))
                builder.append("-----------------------------------------------------------------------\n")
                progress += 7
                it.onNext(ProgressAndDetail(progress, builder.toString()))
            }

            // 3.okhttp访问链接
            val urls = arrayOf(
                "https://api.ghzs.com/v3d3/index/columns",
                "https://download.ghzs.com/game?id=55097638fc1a6fa45f8b4568&platform=9u",
                "https://apk.ghzs666.com/packed/5af00abc02b30f7c038b456c.apk",
                "http://image.ghzs666.com/pic/5b29b3c92924bcaf5d438d38.jpg",
                "http://image.ghzhushou.com/pic/586cad378ab49e0f1b91b3e8.png"
            )
            for (url in urls) {
                builder.append("Url:")
                builder.append(url)
                builder.append("\n")

                val client = OkHttpClient()
                val request = Request.Builder()
                    .head()
                    .url(url)
                    .build()
                try {
                    val response = client.newCall(request).execute()
                    builder.append("Success:\n")
                    builder.append("Response:\n")
                    builder.append(response.toString())
                    builder.append("\n")
                    builder.append("Response Header:\n")
                    builder.append(response.headers().toString())
                    builder.append("\n")
                } catch (e: IOException) {
                    builder.append("Error:\n")
                    builder.append(Log.getStackTraceString(e))
                }
                builder.append("-----------------------------------------------------------------------\n")
                progress += 7
                it.onNext(ProgressAndDetail(progress, builder.toString()))
            }

            it.onComplete()
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ProgressAndDetail>() {
                override fun onNext(response: ProgressAndDetail) {
                    mResult.text = response.detail
                    setResultProgress(response.progress ?: 0)
                }

                override fun onComplete() {
                    initWebView()
                }
            })

    }

    fun setResultProgress(progress: Int) {
        mProgress.text = "正在进行网络诊断 $progress%"
        mBaseHandler.post {
            mScrollView.fullScroll(ScrollView.FOCUS_DOWN)
        }

        mProgressData = progress
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun initWebView() {
        mWebView.loadUrl("https://cdn.dns-detect.alicdn.com/https/doc.html")
        // 开启JavaScript
        mWebView.settings.javaScriptEnabled = true
        // 开启LocalStorage
        mWebView.settings.domStorageEnabled = true
        // 监听页面加载完成
        mWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)

                // 等待10秒，等待js检查完成
                view.postDelayed({
                    // WebView生成长图，也就是超过一屏的图片，代码中的bitmap就是最后生成的长图
                    tryCatchInRelease {
                        mWebView.measure(
                            View.MeasureSpec.makeMeasureSpec(
                                View.MeasureSpec.UNSPECIFIED,
                                View.MeasureSpec.UNSPECIFIED
                            ),
                            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                        )
                        mWebView.layout(0, 0, mWebView.measuredWidth, mWebView.measuredHeight)
                        mWebView.isDrawingCacheEnabled = true
                        mWebView.buildDrawingCache()
                        val bitmap = Bitmap.createBitmap(
                            mWebView.measuredWidth,
                            mWebView.measuredHeight, Bitmap.Config.ARGB_8888
                        )

                        // 画布的宽高和WebView的网页保持一致
                        val canvas = Canvas(bitmap)
                        val paint = Paint()
                        canvas.drawBitmap(bitmap, 0F, mWebView.measuredHeight.toFloat(), paint)
                        mWebView.draw(canvas)

                        // 保存成文件
                        val filePath = bitmap2File(bitmap)

                        builder.append("WebView Long Image Path:\n")
                        builder.append(filePath)
                        builder.append("\n")
                        builder.append("\n")
                        builder.append(mSuccessHint)
                        mSuggestBtn.run {
                            visibility = View.VISIBLE
                            setOnClickListener {
                                val directUtils = ARouter.getInstance().build(RouteConsts.provider.directUtils)
                                    .navigation() as? IDirectProvider
                                directUtils?.directToSuggestionFromDiagnosis(
                                    this@NetworkDiagnosisActivity,
                                    builder.toString().replace(mSuccessHint, "")
                                )
                            }
                        }

                        builder.setSpan(object : ClickableSpan() {
                            override fun updateDrawState(ds: TextPaint) {
                                super.updateDrawState(ds)
                                ds.color = resources.getColor(R.color.theme_font)
                                ds.isUnderlineText = false
                            }

                            override fun onClick(widget: View) {
                                builder.toString().replace(mSuccessHint, "").copyTextAndToast("复制成功")
                            }
                        }, builder.length - mSuccessHint.length, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                        mResult.text = builder
                        mResult.movementMethod = LinkMovementMethod.getInstance()
                        setResultProgress(100)
                    }
                }, 1000)
            }
        }
    }

    fun bitmap2File(bitmap: Bitmap): String {
        try {
            val file = File(
                Environment.getExternalStorageDirectory().absolutePath + "/Pictures/ghzhushou/"
                        + (UUID.randomUUID().toString().replace("-".toRegex(), ""))
                        + ".jpg"
            )
            if (!file.exists()) {
                file.parentFile.mkdirs()
                file.createNewFile()
            }
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)
            fos.flush()
            fos.close()
            return file.absolutePath;
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return ""
    }

    override fun handleBackPressed(): Boolean {
        return if (mProgressData < 100) {
            DialogHelper.showDialog(this, "确认退出", "网络诊断还未完成，退出会终止所有诊断进程，确定退出吗？", "确定", "取消", {
                finish()
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
            true
        } else {
            false
        }

    }
}