package com.gh.gamecenter.setting.view

import android.annotation.SuppressLint
import android.app.Activity
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 androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
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(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.theme_font
                    )
                )
            } else if (msg.what == 1) {
                mBinding.updateItem.contentTv.setText(R.string.toast_upload_latest)
            }
        }
    }

    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)

        if (arguments != null && requireArguments().getBoolean(EntranceConsts.KEY_VERSION_UPDATE)) {
            val updateManager = ARouter.getInstance().build(RouteConsts.provider.updateManager).navigation() as? IUpdateManagerProvider
            updateManager?.checkUpdate(requireContext(), false, mBaseHandler) // 检查更新
        }

        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 = ARouter.getInstance().build(RouteConsts.provider.app).navigation() as? IAppProvider
                toast(appProvider?.getChannel())
            }
            false
        }
    }


    @SuppressLint("SetTextI18n")
    private fun initView() {
        val packageUtils = ARouter.getInstance().build(RouteConsts.provider.packageUtils).navigation() as? IPackageUtilsProvider
        val webActivity = ARouter.getInstance().build(RouteConsts.provider.webActivity).navigation() as? IWebProvider

        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 = ARouter.getInstance().build(RouteConsts.provider.app).navigation() as? IAppProvider
                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 = ARouter.getInstance().build(RouteConsts.provider.updateManager).navigation() as? IUpdateManagerProvider
                updateManager?.checkUpdate(requireContext(), false, mBaseHandler) // 检查更新
            }
        }
        mBinding.userProtocolItem.run {
            titleTv.text = "用户协议"
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "用户协议")
                startActivity(
                    webActivity?.getWebIntent(
                        requireContext(),
                        requireContext().getString(R.string.disclaimer_title),
                        requireContext().getString(R.string.disclaimer_url)
                    )
                )
            }
        }
        mBinding.privacyPolicyItem.run {
            titleTv.text = "隐私政策"
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "关于光环", "隐私政策")
                startActivity(
                    webActivity?.getWebIntent(
                        requireContext(),
                        requireContext().getString(R.string.privacy_policy_title),
                        requireContext().getString(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 = ARouter.getInstance().build(RouteConsts.provider.directUtils).navigation() as? IDirectProvider
                directUtils?.directDouyin(requireContext(), "1402577827140941")
            }
        }
        mBinding.aboutBottom.setOnLongClickListener {
            MtaHelper.onEvent("我的光环_设置", "关于光环", "底部长按")
            if (context == null) return@setOnLongClickListener true
            if (context is Activity && (context as Activity).isFinishing) return@setOnLongClickListener true
            startActivity(webActivity?.getSecurityCertificationIntent(requireContext()))
            true
        }
        mBinding.aboutTvVersion.setOnLongClickListener {
//            String tinkerId = TinkerManager.getNewTinkerId();
//            if (!TextUtils.isEmpty(tinkerId)) {
//                mVersionName.setText(("V" + PackageUtils.getVersionName() + "." + tinkerId));
//            } else {

            toastLong(R.string.toast_upload_latest)
//            }
            false
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.root.setBackgroundColor(R.color.background.toColor(requireContext()))
    }
}