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

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.BuildConfig
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.Config
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.entity.WechatConfigEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserRepository
import com.gh.gamecenter.login.utils.LoginUtils
import com.gh.gamecenter.setting.compose.R
import com.gh.gamecenter.setting.compose.base.ComposeBaseActivity
import com.gh.gamecenter.setting.compose.clickableWithoutRipple
import com.gh.gamecenter.setting.compose.ui.component.SettingDivider
import com.gh.gamecenter.setting.compose.ui.component.SettingItem
import com.gh.gamecenter.setting.compose.ui.component.SettingTopAppBar
import com.gh.gamecenter.setting.compose.ui.component.Space
import com.gh.gamecenter.setting.compose.ui.theme.*
import com.gh.gamecenter.setting.compose.viewmodel.ComposeSettingViewModel
import com.gh.gid.GidHelper
import com.lightgame.download.FileUtils
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus

class ComposeSettingActivity : ComposeBaseActivity() {

    private var mUsageStatus by mutableStateOf(false)
    private var mNotificationAuthoritySwitch by mutableStateOf(false)
    private var mWeChatBindText by mutableStateOf("")
    private var mAboutText by mutableStateOf("")
    private var mIsUpdate by mutableStateOf(false)
    private var mIsLogin by mutableStateOf(false)

    private val mViewModel: ComposeSettingViewModel by viewModels()
    private var loadingDialog: Dialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        mIsUpdate = intent.getBooleanExtra(EntranceConsts.KEY_VERSION_UPDATE, false)
        initLoginStatus()
        initUsageStats()
        initWechatBindStatus()
        initAboutText()
        mViewModel.getCacheSize()
        super.onCreate(savedInstanceState)
    }

    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Composable
    override fun Content() {
        var followSystemDarkModeSwitch by remember {
            mutableStateOf(DarkModeUtils.isFollowSystemDarkModeFromSp())
        }
        var personalRecommendSwitch by remember {
            mutableStateOf(
                SPUtils.getBoolean(
                    Constants.SP_PERSONAL_RECOMMEND,
                    true
                )
            )
        }

        Scaffold(
            topBar = {
                SettingTopAppBar("设置") {
                    onBackPressed()
                }
            }, modifier = Modifier.fillMaxSize(),
            backgroundColor = HaloTheme.colors.background
        ) {
            Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
                if (Config.isExistHideFunction()) {
                    OneKeyFixButton {
                        Config.fixHideFunction()
                        Utils.toast(this@ComposeSettingActivity, "修复成功")
                        EventBus.getDefault().post(EBReuse("Refresh"))
                        val mainActivity = ARouter.getInstance().build(RouteConsts.provider.mainActivity)
                            .navigation() as? IMainProvider
                        mainActivity?.skipToMainActivity(this@ComposeSettingActivity, 0)
                    }
                }
                Space(8.dp)
                SettingItem(getString(R.string.setting_security), showArrow = true) {
                    ifLogin("设置-账号与安全-请先登录") {
                        startActivityForResult(
                            ComposeSecurityActivity.getIntent(
                                this@ComposeSettingActivity,
                                mEntrance,
                                false
                            ), INSERT_MOBILE_CODE
                        )
                    }
                }
                Space(8.dp)
                SettingItem(
                    getString(R.string.setting_system_dark_mode),
                    showSwitch = true,
                    switchStatus = followSystemDarkModeSwitch
                ) {
                    val isDarkModeOn = DarkModeUtils.isDarkModeOn(this@ComposeSettingActivity)
                    NewFlatLogUtils.logHaloSelfNightModeOsSwitch(!followSystemDarkModeSwitch)
                    DarkModeUtils.updateFollowSystemDarkModeToSp(!followSystemDarkModeSwitch)
                    DarkModeUtils.updateAppDarkModeStatusToSp(isDarkModeOn)
                    DarkModeUtils.initDarkMode()
                    followSystemDarkModeSwitch = !followSystemDarkModeSwitch
                }
                Space(8.dp)
                SettingItem(getString(R.string.setting_video), showArrow = true) {
                    startActivity(ComposeVideoSettingActivity.getIntent(this@ComposeSettingActivity, "设置"))
                }
                SettingDivider()
                SettingItem(getString(R.string.setting_game_download), showArrow = true) {
                    startActivity(ComposeGameDownloadSettingActivity.getIntent(this@ComposeSettingActivity, "设置"))
                }
                SettingDivider()
                SettingItem(getString(R.string.setting_game_submission), showArrow = true) {
                    ifLogin("设置-游戏投稿-请先登录") {
                        PermissionHelper.checkStoragePermissionBeforeAction(
                            this@ComposeSettingActivity
                        ) {
                            ARouter.getInstance().build(RouteConsts.activity.gameSubmissionActivity)
                                .withString(
                                    EntranceConsts.KEY_ENTRANCE,
                                    BaseActivity.mergeEntranceAndPath(mEntrance, "游戏上传")
                                )
                                .navigation()
                        }
                    }
                }
                val browserInstallHelper = ARouter.getInstance().build(RouteConsts.provider.browserInstallHelper)
                    .navigation() as? IBrowserInstallHelperProvider
                if (browserInstallHelper?.isUseBrowserToInstallEnabled() == true) {
                    SettingDivider()
                    SettingItem(
                        getString(R.string.setting_install_method),
                        showArrow = true,
                        content = if (browserInstallHelper.shouldUseBrowserToInstall()) "浏览器安装" else "助手安装"
                    ) {
                        val shellActivity = ARouter.getInstance().build(RouteConsts.provider.shellActivity)
                            .navigation() as? IShellProvider
                        val intent = shellActivity?.getSwitchInstallMethodIntent(this@ComposeSettingActivity, null)
                        startActivity(intent)
                        browserInstallHelper.logSwitchInstallSettingEvent()
                    }
                }
                Space(8.dp)
                SettingItem(getString(R.string.setting_usage_stats), showSwitch = true, switchStatus = mUsageStatus) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                        val usageStatsHelper = ARouter.getInstance().build(RouteConsts.provider.usageStatsHelper)
                            .navigation() as? IUsageStatsHelperProvider
                        if (usageStatsHelper?.checkForPermission() == true) {
                            DialogHelper.showDialog(this@ComposeSettingActivity, "提示",
                                "关闭后将无法统计游戏时长，确定要关闭吗？",
                                "确定关闭",
                                "暂不关闭",
                                {
                                    usageStatsHelper.skipToUsageStats(
                                        this@ComposeSettingActivity,
                                        USAGE_STATUS_REQUEST_CODE
                                    )
                                }, {}, DialogHelper.Config(centerContent = true, centerTitle = true)
                            )
                        } else {
                            val dialogUtils = ARouter.getInstance().build(RouteConsts.provider.dialogUtils)
                                .navigation() as? IDialogUtilsProvider
                            dialogUtils?.showUsageStatsDialog(
                                this@ComposeSettingActivity, {
                                    usageStatsHelper?.skipToUsageStats(
                                        this@ComposeSettingActivity,
                                        USAGE_STATUS_REQUEST_CODE
                                    )
                                }, {}
                            )
                        }
                    }
                }
                SettingDivider()
                SettingItem(getString(R.string.setting_wechat_remind), showArrow = true, content = mWeChatBindText) {
                    if (UserManager.getInstance().isLoggedIn) {
                        val json = SPUtils.getString(Constants.SP_WECHAT_CONFIG)
                        val entity = GsonUtils.fromJson(json, WechatConfigEntity::class.java)
                        if (entity != null) {
                            NewLogUtils.logWechatRemindConfigClick(entity.bind, entity.follow, entity.notice)
                        }
                        val webActivity =
                            ARouter.getInstance().build(RouteConsts.provider.webActivity).navigation() as? IWebProvider
                        startActivity(webActivity?.getBindWechatIntent(this@ComposeSettingActivity))
                        SensorsBridge.trackEvent("AppointmenWechatRemindConfigPageShow", "source_entrance", "设置-微信提醒")
                    } else {
                        ifLogin("我的光环_设置") {}
                    }
                }
                SettingDivider()
                SettingItem(
                    getString(R.string.setting_notification_authority),
                    tips = getString(R.string.setting_notification_authority_hint),
                    showSwitch = true,
                    switchStatus = mNotificationAuthoritySwitch
                ) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                        val notifyIntent = Intent()
                        notifyIntent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                        val buildConfig = ARouter.getInstance().build(RouteConsts.provider.buildConfig)
                            .navigation() as? IBuildConfigProvider
                        notifyIntent.putExtra(Settings.EXTRA_APP_PACKAGE, buildConfig?.getApplicationId())
                        startActivity(notifyIntent)
                    } else {
                        PermissionHelper.toPermissionSetting(this@ComposeSettingActivity)
                    }
                }
                SettingDivider()
                SettingItem(
                    getString(R.string.setting_personal_recommend),
                    tips = getString(R.string.setting_personal_recommend_hint),
                    showSwitch = true,
                    switchStatus = personalRecommendSwitch
                ) {
                    SPUtils.setBoolean(Constants.SP_PERSONAL_RECOMMEND, !personalRecommendSwitch)
                    personalRecommendSwitch = !personalRecommendSwitch
                }
                Space(8.dp)
                SettingItem(
                    if (PackageFlavorHelper.IS_TEST_FLAVOR) getString(R.string.setting_about_channel) else getString(
                        R.string.setting_about
                    ), content = mAboutText, showUpdateHint = mIsUpdate, onLongClick = {
                        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
                            showChangeChannelDialog()
                        }
                    }) {
                    val mIsUpdate = intent.getBooleanExtra(EntranceConsts.KEY_VERSION_UPDATE, false)
                    startActivity(ComposeAboutActivity.getIntent(this@ComposeSettingActivity, mIsUpdate))
                }
                Space(8.dp)
                SettingItem(
                    if (PackageFlavorHelper.IS_TEST_FLAVOR) getString(R.string.setting_clear_cache) + "(长按可清除gid)" else getString(
                        R.string.setting_clear_cache
                    ), content = mViewModel.cacheSizeState, onLongClick = {
                        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
                            GidHelper.getInstance().clearSavedGid()
                            Utils.toast(this@ComposeSettingActivity, "gid已清除")
                        }
                    }) {
                    DialogHelper.showCenterWarningDialog(
                        this@ComposeSettingActivity, "清除缓存", "确定要清除缓存吗？"
                    ) {
                        val dialogUtils = ARouter.getInstance().build(RouteConsts.provider.dialogUtils)
                            .navigation() as? IDialogUtilsProvider
                        loadingDialog = dialogUtils?.showWaitDialog(this@ComposeSettingActivity, "清除缓存中...")
                        val historyHelper = ARouter.getInstance().build(RouteConsts.provider.historyHelper)
                            .navigation() as? IHistoryHelperProvider
                        historyHelper?.emptyDatabase()
                        clearCache()
                    }
                }
                SettingDivider()
                SettingItem(getString(R.string.setting_network_diagnosis)) {
                    startActivity(Intent(this@ComposeSettingActivity, NetworkDiagnosisActivity::class.java))
                }
                if (mIsLogin) {
                    Space(8.dp)
                    LogoutButton {
                        val dialogUtils = ARouter.getInstance().build(RouteConsts.provider.dialogUtils)
                            .navigation() as? IDialogUtilsProvider
                        DialogHelper.showDialog(
                            this@ComposeSettingActivity,
                            R.string.logout_dialog_title.toResString(),
                            R.string.logout_dialog_content.toResString(),
                            R.string.logout_dialog_confirm.toResString(),
                            R.string.cancel.toResString(),
                            {
                                loadingDialog = dialogUtils?.showWaitDialog(this@ComposeSettingActivity, "退出登录中...")
                                LoginUtils.logout {
                                    UserRepository.getInstance().logout()
                                    if (loadingDialog != null) loadingDialog!!.dismiss()
                                    finish()
                                }
                            },
                            extraConfig = DialogHelper.Config(
                                centerTitle = true,
                                centerContent = true
                            ),
                            uiModificationCallback = {
                                it.confirmTv.setTextColor(R.color.theme_red.toColor(this@ComposeSettingActivity))
                            }
                        )
                    }
                    Space(48.dp)
                }
            }
        }
    }


    private fun initLoginStatus() {
        val loginToken = UserManager.getInstance().loginTokenEntity
        mIsLogin = loginToken != null
    }

    private fun initAboutText() {
        if (mIsUpdate) {
            mAboutText = ""
        } else {
            // Jenkins 打的包附带个打包时间在版本后面
            val packageUtils =
                ARouter.getInstance().build(RouteConsts.provider.packageUtils).navigation() as? IPackageUtilsProvider
            mAboutText = if (BuildConfig.BUILD_TIME == 0L) {
                "V" + packageUtils?.getGhVersionName()
            } else {
                "V" + packageUtils?.getGhVersionName() + " " + BuildConfig.BUILD_TIME
            }
            if (PackageFlavorHelper.IS_TEST_FLAVOR) {
                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() ?: ""
                }
                mAboutText = "($channel)"
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mNotificationAuthoritySwitch = NotificationHelper.notificationIsEnable()
    }

    private fun initUsageStats() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            return
        }
        val usageStatsHelper = ARouter.getInstance().build(RouteConsts.provider.usageStatsHelper)
            .navigation() as? IUsageStatsHelperProvider
        if (usageStatsHelper?.checkForPermission() == true && SPUtils.getBoolean(Constants.SP_USAGE_STATUS, true)) {
            mUsageStatus = true
        } else {
            mUsageStatus = false
        }
    }

    private fun initWechatBindStatus() {
        if (UserManager.getInstance().isLoggedIn) {
            val json = SPUtils.getString(Constants.SP_WECHAT_CONFIG)
            val notice = GsonUtils.fromJson(json, WechatConfigEntity::class.java).notice
            mWeChatBindText = if (notice) "已开启" else "已关闭"
        } else {
            mWeChatBindText = ""
        }
    }

    private fun showChangeChannelDialog() {
        val layout = LinearLayout(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            gravity = Gravity.CENTER
            setPadding(0, DisplayUtils.dip2px(16f), 0, 0)
        }

        val editText = EditText(this)
        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() ?: ""
            SPUtils.setString(Constants.SP_TEST_FLAVOR_CHANNEL, channel)
        }
        editText.setText(channel, TextView.BufferType.EDITABLE)
        editText.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            leftMargin = DisplayUtils.dip2px(16F)
            rightMargin = DisplayUtils.dip2px(16F)
        }
        layout.addView(editText)
        val inputDialog: AlertDialog.Builder = AlertDialog.Builder(this)
        inputDialog.setTitle("请输入渠道：").setView(layout)
        inputDialog.setPositiveButton("确定") { _, _ ->
            if (!TextUtils.isEmpty(editText.text)) {
                SPUtils.setString(Constants.SP_TEST_FLAVOR_CHANNEL, editText.text.toString())
                val appProvider = ARouter.getInstance().build(RouteConsts.provider.app).navigation() as? IAppProvider
                appProvider?.setChannel(editText.text.toString())
            }
        }.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == USAGE_STATUS_REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            val usageStatsHelper = ARouter.getInstance().build(RouteConsts.provider.usageStatsHelper)
                .navigation() as? IUsageStatsHelperProvider
            SPUtils.setBoolean(Constants.SP_USAGE_STATUS, usageStatsHelper?.checkForPermission() == true)
            initUsageStats()
        }
        // 当前登录方式为手机号登录，更换手机号后，回到该界面更新"退出账号"的手机号
        if (requestCode == INSERT_MOBILE_CODE) {
            initLoginStatus()
        }
    }

    // 清除缓存
    private fun clearCache() {
        Observable.create { emitter: ObservableEmitter<Any?> ->
            val start = System.currentTimeMillis()
            FileUtils.deleteFolder(cacheDir)
            FileUtils.deleteFolder(externalCacheDir)
            val time = System.currentTimeMillis() - start
            if (time < 1000) {
                try {
                    Thread.sleep(1000 - time)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }

//                Fresco.getImagePipeline().clearCaches(); // 清空图片缓存
            emitter.onComplete()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Any?> {
                override fun onComplete() {
                    if (loadingDialog != null) {
                        loadingDialog!!.dismiss()
                    }
                    mViewModel.getCacheSize()
                    Utils.toast(this@ComposeSettingActivity, "缓存清除成功")
                }

                override fun onError(e: Throwable) {
                    // do nothing
                }
                override fun onSubscribe(d: Disposable) {
                    // do nothing
                }
                override fun onNext(t: Any) {
                    // do nothing
                }
            })
    }

    companion object {
        const val INSERT_MOBILE_CODE = 411
        const val USAGE_STATUS_REQUEST_CODE = 233

        fun getIntent(context: Context, isUpdate: Boolean, entrance: String): Intent {
            return Intent(context, ComposeSettingActivity::class.java).apply {
                putExtra(EntranceConsts.KEY_ENTRANCE, entrance)
                putExtra(EntranceConsts.KEY_VERSION_UPDATE, isUpdate)
            }
        }
    }
}

@Composable
fun OneKeyFixButton(onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 15.dp)
            .clickableWithoutRipple(onClick)
            .background(Color(0XFFFF4E00)),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = "一键修复", fontSize = 18.sp, color = Color.White)
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LogoutButton(onClick: () -> Unit) {
    var isPressed by remember {
        mutableStateOf(false)
    }
    Row(modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .pointerInteropFilter {
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    isPressed = true
                }
                MotionEvent.ACTION_CANCEL -> {
                    isPressed = false
                }
                MotionEvent.ACTION_UP -> {
                    isPressed = false
                    onClick.invoke()
                }
            }
            true
        }
        .background(if (isPressed) Color(0X0D000000) else HaloTheme.colors.backgroundWhite),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically)
    {
        Text(text = "退出登录", fontSize = 15.sp, color = HaloTheme.colors.textTitle)
    }
}
