package com.gh.gamecenter.setting.view

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.preference.PreferenceManager
import android.text.TextUtils
import android.view.View
import com.therouter.TheRouter
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.common.utils.copyTextAndToast
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.provider.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.setting.R
import com.gh.gamecenter.setting.databinding.FragmentAboutBinding
import java.util.*

class AboutFragment : ToolbarFragment() {

    private lateinit var mBinding: FragmentAboutBinding

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentAboutBinding.inflate(layoutInflater).apply { mBinding = this }.root

    // update callback
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (isAdded) {
            if (msg.what == 0) {
                val version = msg.obj as String
                mBinding.updateItem.contentTv.text = StringUtils.buildString("发现新版本 V", version)
                mBinding.updateItem.contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
            } else if (msg.what == 1) {
                mBinding.updateItem.contentTv.setText(R.string.toast_upload_latest)
                mBinding.updateItem.contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(requireContext()))
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setNavigationTitle(getString(R.string.title_about))
        initView()

        val serverTime = PreferenceManager.getDefaultSharedPreferences(requireContext())
            .getLong("server_time", 1587693163L)
        val year = TimeUtils.getFormatTime(serverTime, "yyyy")
        mBinding.copyrightTv.text = getString(R.string.copyright_hint, year)

        val updateManager = TheRouter.get(IUpdateManagerProvider::class.java)
        updateManager?.checkUpdate(requireActivity(), true) // 检查更新

        var clickCount = 0
        mBinding.aboutGhIcon.setOnClickListener {
            if (clickCount == 5) {
                mBinding.aboutGhIcon.setOnClickListener(null)
                mBinding.deviceContent.visibility = View.VISIBLE
                mBinding.deviceContent.text.toString().copyTextAndToast("复制成功！")
            } else {
                clickCount++
            }
        }

        mBinding.aboutGhIcon.setOnLongClickListener {
            MtaHelper.onEvent("我的光环_设置", "关于光环", "图标长按")
            if (PackageFlavorHelper.IS_TEST_FLAVOR) {
                DialogHelper.showDialog(
                    requireContext(),
                    "重选接口环境",
                    "是否要清空应用数据并重选接口环境\n(清空后数据后需要手动再打开 APP)",
                    "是",
                    "否", {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            (requireContext().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).clearApplicationUserData()
                        } else {
                            ToastUtils.toast("低版本系统不支持自动清空应用数据，请手动到应用管理里清除")
                        }
                    }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
            } else {
                val appProvider = TheRouter.get(IAppProvider::class.java)
                toast(appProvider?.getChannel())
            }
            false
        }

        val appProvider = TheRouter.get(IAppProvider::class.java)
        if (appProvider?.getFlavor() != "publish") {
            val pkgConfigProvider = TheRouter.get(IPkgConfigProvider::class.java)
            var clickCount = 0
            mBinding.appNameTv.setOnClickListener {
                clickCount = clickCount + 1
                if (clickCount % 5 == 0) {
                    val configList = pkgConfigProvider?.getPkgConfig()
                    var configString = ""
                    configList?.forEach {
                        if (it.isNotEmpty()) {
                            configString = "$configString$it\n"
                        }
                    }
                    toastLong(configString)
                }
            }
        }

        mBinding.aboutTvVersion.setOnLongClickListener {
            appProvider?.let {
                val pluginVersion = it.getPluginVersion()
                if(pluginVersion.isNotEmpty()) {
                    toast("插件：V${pluginVersion}")
                }
            }
            false
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        val packageUtils = TheRouter.get(IPackageUtilsProvider::class.java)
        val webActivity = TheRouter.get(IWebProvider::class.java)

        mBinding.aboutTvVersion.text = "V" + packageUtils?.getGhVersionName()

        if (PackageFlavorHelper.IS_TEST_FLAVOR == true) {
            var channel = SPUtils.getString(Constants.SP_TEST_FLAVOR_CHANNEL)
            if (channel == null || TextUtils.isEmpty(channel)) {
                val appProvider = TheRouter.get(IAppProvider::class.java)
                channel = appProvider?.getChannel() ?: ""
            }
            mBinding.aboutTvVersion.text = "V" + packageUtils?.getGhVersionName() + "（$channel）"

        }
        mBinding.updateItem.run {
            titleTv.text = getString(R.string.about_version_update)
            contentTv.text = ""
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "版本更新")
                val updateManager = TheRouter.get(IUpdateManagerProvider::class.java)
                updateManager?.checkUpdate(requireActivity(), true) // 检查更新
            }
        }
        mBinding.userProtocolItem.run {
            titleTv.text = "用户协议"
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "用户协议")
                startActivity(
                    webActivity?.getWebIntent(
                        requireContext(),
                        requireContext().getString(com.gh.gamecenter.common.R.string.disclaimer_title),
                        requireContext().getString(com.gh.gamecenter.common.R.string.disclaimer_url)
                    )
                )
            }
        }
        mBinding.privacyPolicyItem.run {
            titleTv.text = "隐私政策"
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "隐私政策")
                startActivity(
                    webActivity?.getWebIntent(
                        requireContext(),
                        requireContext().getString(com.gh.gamecenter.common.R.string.privacy_policy_title),
                        requireContext().getString(com.gh.gamecenter.common.R.string.privacy_policy_url)
                    )
                )
            }
        }
        mBinding.douyinItem.run {
            titleTv.text = "官方抖音"
            textMoreTv.text = "光环助手APP"
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "抖音")
                val url = getString(R.string.gh_douyin_url)
                url.copyTextAndToast(String.format(Locale.CHINA, "已成功复制%s ，打开抖音可直达", url))
                val directUtils = TheRouter.get(IDirectProvider::class.java)
                directUtils?.directDouyin(requireContext(), "1402577827140941")
            }
        }

        mBinding.deviceContent.run {
            val sb = StringBuilder()
            val meta = MetaUtil.getMeta()
            val pushId = TheRouter.get(IPushProvider::class.java)?.getRegistrationId(context) ?: "unknown"

            sb.append("OAID: ").append(meta.oaid).append("\n")
            sb.append("ANDROID_ID: ").append(MetaUtil.getAndroidId()).append("\n")
            sb.append("GID: ").append(meta.gid).append("\n")
            sb.append("USER_ID: ").append(meta.userId).append("\n")
            sb.append("CHANNEL: ").append(meta.channel).append("\n")
            sb.append("APP_VERSION: ").append(meta.appVersion).append("\n")
            sb.append("PUSH_ID: ").append(pushId)
            text = sb.toString()
        }

        mBinding.icpTv.setOnClickListener {
            val directUtils = TheRouter.get(IDirectProvider::class.java)
            directUtils?.directToExternalBrowser(requireContext(), requireContext().getString(com.gh.gamecenter.common.R.string.icp_url))
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
    }
}