package com.mints.goodmoney.ui.fragment

import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebViewClient
import com.mints.goodmoney.R
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.ui.fragment.base.LazyLoadBaseFragment
import com.mints.goodmoney.utils.LogUtil
import com.mints.goodmoney.utils.MD5
import com.mints.goodmoney.utils.URIEncoder
import kotlinx.android.synthetic.main.fragment_main_dh.*


/**
 * 描述：电魂游戏
 * 作者：孟崔广
 */
class DhGameFragment : LazyLoadBaseFragment(), View.OnClickListener {

    companion object {
        const val CHANNEL = "14533"
        const val KEY = "4932d9037fd94f6ba24fa09605203cd6"
        const val AUTH_URL = "http://www.shandw.com/auth/"
    }

    private val TAG = DhGameFragment::class.java.simpleName

    override fun getContentViewLayoutID() = R.layout.fragment_main_dh

    override fun initViewsAndEvents() {
    }

    override fun onFragmentFirstVisible() {
        loadH5Game()
        initListener()
    }

    override fun onDestroy() {
        super.onDestroy()

        dh_webview?.let {
            it.destroyDrawingCache()
            val parent = it.getParent() as ViewGroup
            parent.removeView(it)
            it.removeAllViews()
            it.destroy()
        }

    }

    override fun onClick(v: View) {
        when (v?.id) {
            R.id.ivDhBack -> {
                dh_webview.goBack()
            }
            R.id.tvDhRefresh -> {
                loadH5Game()
            }
        }
    }

    /**
     * 加载H5Game
     */
    private fun loadH5Game() {
        dh_webview?.let {
            var loadUrl = getLoadUrl()
            LogUtil.d(TAG, "url-->${loadUrl}")
            val settings = it.settings
            // 本地 DOM 存储（解决加载某些网页出现白板现象）
            settings.domStorageEnabled = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 解决 Android 5.0 上 WebView 默认不允许加载 Http 与 Https 混合内容
                settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
            settings.javaScriptEnabled = true
            settings.javaScriptCanOpenWindowsAutomatically = true
            it.setWebViewClient(object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                        view: android.webkit.WebView,
                        url: String
                ): Boolean {
                    if (url.startsWith("weixin://wap/pay?") || url.startsWith("alipay")) {
                        val hasApp: Boolean
                        hasApp = if (url.startsWith("weixin://wap/pay?")) {
                            isAppExist("com.tencent.mm")
                        } else {
                            (isAppExist("com.eg.android.AlipayGphone") || isAppExist("com.alipay.android.app"))
                        }
                        if (hasApp) {
                            val intent = Intent()
                            intent.action = Intent.ACTION_VIEW
                            intent.data = Uri.parse(url)
                            activity?.startActivity(intent)
                        } else {
                            showToast("客官，请先安装支付App哦~")
                        }
                        return true
                    }

                    if (url.startsWith("https")) {
                        val map = HashMap<String, String>()
                        map["Referer"] = "http://www.shandw.com"
                        it.loadUrl(url, map)
                    }
                    return super.shouldOverrideUrlLoading(view, url)
                }
            })
            it.loadUrl(loadUrl)
        }
    }

    /**
     * 获取拼接url
     */
    fun getLoadUrl(): String {
        val currentTimeMillis = System.currentTimeMillis() / 1000
        var loadUrl = "${AUTH_URL}?" +
                "channel=${CHANNEL}&" +
                "openid=${URIEncoder.encodeURIComponent(UserManager.getInstance().userID)}&" +
                "time=${currentTimeMillis}&" +
                "nick=${URIEncoder.encodeURIComponent(UserManager.getInstance().userID)}&" +
                "avatar=${URIEncoder.encodeURIComponent("https://mints-pkg.oss-cn-beijing.aliyuncs.com/pkg_goodmoney/img/ic_my.png")}&" +
                "sex=${0}&" +
                "phone=${UserManager.getInstance().mobile}&" +
                "sdw_simple=${2}&" +
                "sign=${getSignStr(currentTimeMillis)}"
        return loadUrl
    }

    /**
     * 获取签名
     */
    fun getSignStr(currentTimeMillis: Long): String {
        val signStr = "channel=${CHANNEL}&" +
                "openid=${URIEncoder.encodeURIComponent(UserManager.getInstance().userID)}&" +
                "time=${currentTimeMillis}&" +
                "nick=${UserManager.getInstance().userID}&" +
                "avatar=https://mints-pkg.oss-cn-beijing.aliyuncs.com/pkg_goodmoney/img/ic_my.png&" +
                "sex=${0}&" +
                "phone=${UserManager.getInstance().mobile}${KEY}"
        return MD5.GetMD5Code(signStr).toLowerCase()
    }

    fun isAppExist(pkgName: String): Boolean {
        var info: ApplicationInfo? = null
        try {
            context?.getPackageManager()!!.getApplicationInfo(pkgName, 0)
            context!!.startActivity(context!!.packageManager.getLaunchIntentForPackage(pkgName))
        } catch (e: Exception) {
        }
        return if (info != null) true else false
    }

    private fun initListener() {
        ivDhBack.setOnClickListener(this)
        tvDhRefresh.setOnClickListener(this)
    }
}