package com.adealink.weparty.debug

import android.annotation.SuppressLint
import android.content.Intent
import androidx.activity.viewModels
import com.adealink.frame.base.AppBase
import com.adealink.frame.debug.datasource.performanceDataController
import com.adealink.frame.debug.floatkit.floatKitManager
import com.adealink.frame.log.data.ReportLogReq
import com.adealink.frame.log.data.ReportLogType
import com.adealink.frame.log.viewmodel.LogViewModel
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.onClick
import com.adealink.weparty.App
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.isUiValid
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.floatview.WindowManagerProxy
import com.adealink.weparty.commonui.widget.floatview.data.MODE_APPLICATION
import com.adealink.weparty.config.approvingVersionManager
import com.adealink.weparty.databinding.ActivityDebugBinding
import com.adealink.weparty.debug.DebugPrefs.testDeviceId
import com.adealink.weparty.log.viewmodel.LogViewModelFactory
import com.adealink.weparty.module.account.AccountLocalService
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.im.IM
import com.adealink.weparty.module.im.IMModule
import com.adealink.weparty.module.room.Room
import com.adealink.weparty.storage.AppPref
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.adealink.weparty.util.goLocalLinkPage
import com.adjust.sdk.Adjust
import com.adjust.sdk.OnIsEnabledListener
import com.google.gson.annotations.SerializedName

@RouterUri(path = [Debug.Debug.PATH], desc = "debug页面")
class DebugActivity : BaseActivity(), OnReturnValue {

    private val binding by viewBinding(ActivityDebugBinding::inflate)
    private val logViewModel by viewModels<LogViewModel> { LogViewModelFactory() }
    private val api = App.instance.networkService.getHttpService(DebugApi::class.java)

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        QMUIStatusBarHelper.setStatusBarLightMode(this)
        setContentView(binding.root)

        //用户/APP信息
        binding.etTestAccount.setText(AccountLocalService.testAccount)
        binding.userInfo.text = "uid: ${AppPref.uid}"
        binding.tvImLogin.text = "IM登录状态: " + if (IMModule.isLogin()) {
            "已登录"
        } else {
            "未登录"
        }
        binding.tvApprovingStatus.text =
            "审核版本: ${approvingVersionManager.getApprovingVersion()}, 审核状态:${approvingVersionManager.isApproving()}" + if (approvingVersionManager.isApproving()) {
                ", 部分功能受限"
            } else {
                ""
            }

        Adjust.isEnabled(this, object : OnIsEnabledListener {
            override fun onIsEnabledRead(p0: Boolean) {
                if (isUiValid()) {
                    binding.tvAdjustStatus.text = "Adjust状态:" + if (p0) {
                        "启用"
                    } else {
                        "可不用"
                    }
                }
            }
        })

        binding.btnSwitchAccount.setOnClickListener {
            val fbAccount = binding.etTestAccount.text.toString()
            if (fbAccount.isEmpty()) {
                return@setOnClickListener
            }
            AccountLocalService.testAccount = fbAccount
            AccountModule.logout(true)
        }
        binding.btnLogout.setOnClickListener {
            AccountModule.logout(true)
        }

        //网络
        binding.httpUrl.setText(DebugPrefs.httpUrl)
//        binding.socketUrl.setText(DebugPrefs.socketUrl)
        binding.webHttpUrl.setText(DebugPrefs.webHttpUrl)
        binding.webHttpUrlBtn.setOnClickListener {
            saveHttpUrl()
//            saveSocketUrl()
            saveWebHttpUrl()
            showToast("请杀死App重启")
        }

        //网络工具
        binding.webUrlEd.setText(DebugPrefs.webUrlEd)
        binding.webUrlEd.setText("https://test-web.gami.vip/recharge?id=692c003e7e4a84752e314020&redirect=/native/callback")
        binding.webUrlBtn.setOnClickListener {
            saveWebUrlEd()
            goWebTest()
        }
        binding.webWhiteHostEd.setText(DebugPrefs.webWhiteHostEd)
        binding.webWhiteHostBtn.setOnClickListener {
            saveWebWhiteHostEd()
            addWhiteHost()
            showToast("请杀死App重启")
        }

        //其他工具
        binding.reportLogBtn.setOnClickListener {
            reportLog()
        }

        if (!AppBase.isRelease) {
            binding.switchSvgaChecker.show()
            binding.tvSvgaChecker.text = getSvgaCheckerText()
            binding.clSvgaChecker.setOnClickListener {
                if (AppBase.isRelease) {
                    showToast("RELEASE包不能设置")
                    return@setOnClickListener
                }
                SvgaCheckerTestDialog.newInstance(this).show(supportFragmentManager)
            }
            binding.clSvgaCheckerResult.show()
            binding.tvSvgaCheckerResult.text = getSvgaCheckResultText()
            binding.clSvgaCheckerResult.setOnClickListener {
                if (AppBase.isRelease) {
                    showToast("RELEASE包不能设置")
                    return@setOnClickListener
                }
                ShowSvgaCheckResultTestDialog.newInstance(this).show(supportFragmentManager)
            }
        } else {
            binding.switchSvgaChecker.gone()
        }

        binding.swPerformanceFloatView.isChecked = DebugPrefs.showPerformanceFloatView
        binding.swPerformanceFloatView.setOnCheckedChangeListener { _, isChecked ->
            DebugPrefs.showPerformanceFloatView = isChecked
            if (isChecked) {
                floatKitManager.install(application, false)
                floatKitManager.onMainIconDoubleClick = {
                    AppUtil.currentActivity?.let {
                        Router.build(it, Debug.Debug.PATH).start()
                    }
                }
                floatKitManager.show()
                performanceDataController.start()
            } else {
                floatKitManager.hide()
                performanceDataController.destroy()
            }
        }

        binding.swPerformanceMonitor.isChecked = isShowMemoryFloatView
        binding.swPerformanceMonitor.setOnCheckedChangeListener { _, isChecked ->
            if (AppBase.isRelease) {
                return@setOnCheckedChangeListener
            }
            isShowMemoryFloatView = isChecked
            if (isChecked) {
                val memoryUsageFloatView =
                    createSysMemoryUsageFloatView() ?: return@setOnCheckedChangeListener
                WindowManagerProxy.getWindowManager().addView(memoryUsageFloatView)
                return@setOnCheckedChangeListener
            }
            sysMemoryUsageFloatView?.let {
                WindowManagerProxy.getWindowManager().removeView(it)
                sysMemoryUsageFloatView = null
            }
        }

        binding.imSessionBtn.onClick {
            val uid = binding.imUidEd.text?.trim()?.toString()
            if (uid.isNullOrEmpty()) {
                return@onClick
            }
            Router.build(this@DebugActivity, IM.Session.PATH)
                .putExtra(IM.Session.EXTRA_CHAT_ID, uid)
                .start()
        }

        binding.uiTestBtn.onClick {
            uiTest()
        }

        binding.deviceidEd.setText(testDeviceId)
        binding.saveDeviceidBtn.onClick {
            saveDeviceId()
        }

        binding.roomEnterBtn.onClick {
            val roomId = binding.roomIdEd.text?.trim()?.toString()
            if (roomId.isNullOrEmpty()) {
                return@onClick
            }
            Router.build(this@DebugActivity, Room.Room.PATH)
                .putExtra(Room.Room.EXTRA_ENTER_ROOM_ID, roomId)
                .start()
        }
    }

    private fun saveWebUrlEd() {
        DebugPrefs.webUrlEd = binding.webUrlEd.text.toString()
    }

    private fun saveWebWhiteHostEd() {
        DebugPrefs.webWhiteHostEd = binding.webWhiteHostEd.text.toString()
    }

    private fun reportLog() {
        val uid = binding.logUidEt.text.toString()
        val uidLong = uid.toLongOrNull() ?: return
        val req = ReportLogReq(uidLong, logTypes = listOf(ReportLogType.USER.type))
        logViewModel.reportLog(req).observe(this) {
            showToast(it)
        }
    }


    private fun saveHttpUrl() {
        val httpUrl = binding.httpUrl.text.toString()
        if (httpUrl.isEmpty()) {
            return
        }

        DebugPrefs.httpUrl = httpUrl
    }

    private fun saveWebHttpUrl() {
        val httpUrl = binding.webHttpUrl.text.toString()
        DebugPrefs.webHttpUrl = httpUrl
        // TODO:
//        Uri.parse(httpUrl).host?.let {
//            App.instance.jsBridgeManager.addWhiteList(listOf(it))
//        }
    }

//    private fun saveSocketUrl() {
//        val socketUrl = binding.socketUrl.text.toString()
//        if (socketUrl.isEmpty()) {
//            return
//        }
//
//        DebugPrefs.socketUrl = socketUrl
//    }

    private fun goWebTest() {
        val webTestUrl = binding.webUrlEd.text.toString()
        if (webTestUrl.isEmpty()) {
            return
        }

        goLocalLinkPage(context = this, webTestUrl)
    }

    private fun addWhiteHost() {
        val whiteHost = binding.webWhiteHostEd.text.toString()
        if (whiteHost.isEmpty()) {
            return
        }

//        App.instance.jsBridgeManager.addWhiteList(listOf(whiteHost))
    }


    interface DebugApi {
//        @POST("config/setRoomListRegion")
//        suspend fun changeRegion(@Body req: ChangeRegionReq): Rlt<Res<Boolean>>
    }

    data class ChangeRegionReq(
        @SerializedName("region")
        val region: String
    )

    override fun clickValue(type: String, value: String?) {
        when (type) {

            SvgaCheckerTestDialog::class.java.name -> {
                binding.tvSvgaChecker.text = getSvgaCheckerText()
                binding.tvSvgaCheckerResult.text = getSvgaCheckResultText()
            }

            ShowSvgaCheckResultTestDialog::class.java.name -> {
                binding.tvSvgaCheckerResult.text = getSvgaCheckResultText()
            }
        }
    }

    private fun getSvgaCheckerText(): String {
        if (AppBase.isRelease) {
            return "RELEASE包不能设置"
        }
        return if (DebugPrefs.enableSvgaChecker) {
            "开启"
        } else {
            "关闭"
        }
    }

    private fun getSvgaCheckResultText(): String {
        if (AppBase.isRelease) {
            return "RELEASE包不能设置"
        }
        if (!DebugPrefs.enableSvgaChecker) {
            return "需要先开启SVGA合规检查"
        }
        return if (DebugPrefs.enableShowSvgaCheckResult) {
            "开启"
        } else {
            "关闭"
        }
    }

    private fun uiTest() {
        startActivity(Intent(this, DebugUIActivity::class.java))
    }

    private fun saveDeviceId() {
        val deviceId = binding.deviceidEd.text?.trim()?.toString()
        if (deviceId.isNullOrEmpty()) {
            return
        }
        testDeviceId = deviceId
        showToast("请杀死App重启")
    }

    companion object {
        var sysMemoryUsageFloatView: SysMemoryUsageFloatView? = null
        var isShowMemoryFloatView = false
        fun createSysMemoryUsageFloatView(): SysMemoryUsageFloatView? {
            if (sysMemoryUsageFloatView != null) {
                return sysMemoryUsageFloatView
            }
            val sysMemoryUsageFloatView = SysMemoryUsageFloatView(
                SysMemoryUsageFloatData(
                    MODE_APPLICATION
                )
            )
            sysMemoryUsageFloatView.onSelfRemovedCallback = {
                isShowMemoryFloatView = false
                this.sysMemoryUsageFloatView = null
            }
            this.sysMemoryUsageFloatView = sysMemoryUsageFloatView
            return this.sysMemoryUsageFloatView
        }
    }
}