package org.yameida.worktool.activity

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.provider.Settings
import android.text.InputType
import android.util.Log
import android.view.WindowManager
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.CompoundButton
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.activity_listen.bt_save
import kotlinx.android.synthetic.main.activity_listen.et_channel
import kotlinx.android.synthetic.main.activity_listen.iv_settings
import kotlinx.android.synthetic.main.activity_listen.sw_accessibility
import kotlinx.android.synthetic.main.activity_listen.sw_overlay
import kotlinx.android.synthetic.main.activity_listen.tv_host
import kotlinx.android.synthetic.main.activity_listen.tv_version
import kotlinx.android.synthetic.main.activity_listen.tv_work_version
import org.yameida.worktool.Constant
import org.yameida.worktool.R
import org.yameida.worktool.model.WeworkMessageBean
import org.yameida.worktool.service.PlayNotifyService
import org.yameida.worktool.service.WeworkController
import org.yameida.worktool.service.fastStartActivity
import org.yameida.worktool.utils.AccessibilityUtil
import org.yameida.worktool.utils.CacheUtil
import org.yameida.worktool.utils.FloatWindowHelper
import org.yameida.worktool.utils.FlowPermissionHelper
import org.yameida.worktool.utils.HostTestHelper
import org.yameida.worktool.utils.HttpUtil
import org.yameida.worktool.utils.PermissionHelper
import org.yameida.worktool.utils.PermissionPageManagement
import org.yameida.worktool.utils.Views
import org.yameida.worktool.utils.capture.MediaProjectionHolder
import org.yameida.worktool.utils.envcheck.CheckHook
import org.yameida.worktool.utils.envcheck.CheckRoot


class ListenActivity : AppCompatActivity() {

    var riskRetry: Int = 0

    val handler = Handler()

    companion object {
        /**
         * @param type 0=游客登录
         */
        fun enterActivity(context: Context, type: Int) {
            LogUtils.d("ListenActivity.enterActivity type: $type")
            context.startActivity(Intent(context, ListenActivity::class.java).apply {
                this.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                putExtra("type", type)
            })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        setContentView(R.layout.activity_listen)
        initView()
        initAccessibility()
        initOverlays()
        initData()
        initNotification()
        PermissionUtils.permission(PermissionConstants.STORAGE,PermissionConstants.PHONE).request()
        registerReceiver(openWsReceiver, IntentFilter(Constant.WEWORK_NOTIFY))
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(openWsReceiver)
    }

    override fun onResume() {
        super.onResume()
        sw_overlay.isChecked =
            Settings.canDrawOverlays(Utils.getApp()) && FlowPermissionHelper.canBackgroundStart(
                Utils.getApp()
            )
        sw_accessibility.isChecked = PermissionHelper.isAccessibilitySettingOn()

        if (needToWork) {
            needToWork = false
            goToWork()
        }
    }

    private fun initView() {
        iv_settings.setOnClickListener {
            SettingsActivity.enterActivity(this)
        }
        et_channel.setText(Constant.robotId)
//        tv_android_id.text = DeviceUtils.getAndroidID()
        bt_save.setOnClickListener {
            val channel = et_channel.text.toString().trim()
            Constant.robotId = channel
            ToastUtils.showLong("保存成功")
            HttpUtil.upgrade(this)
//            bt_save.postDelayed({
//                IWWAPIUtil.sendLink("wwc1f6c9a9876411a6","1000006","https://assistant.flowbb.top/image/f22e830546cff2fdb0eeadfadd58e2bcc54dcf3d3e4088-aw7ly1_fw1200.png",
//                    "https://wx7546b6c93955bad2-a.wxcp.qidian.com/sog/EXXfC","1","1")
//            }, 3000)
//            IWWAPIUtil.init(this)

        }
        tv_host.text = Constant.host
        tv_host.setOnClickListener {
            showSelectHostDialog()
        }
        tv_host.setOnLongClickListener {
            showInputHostDialog()
            true
        }
        val version =
            "${AppUtils.getAppVersionName()}     Android ${DeviceUtils.getSDKVersionName()} ${DeviceUtils.getManufacturer()} ${DeviceUtils.getModel()}"
        val deviceRooted = CheckRoot.isDeviceRooted()
        val hook = CheckHook.isHook(applicationContext)
        if (hook) {
            tv_version.text = "当前设备存在侵入代码，请勿在本设备使用本程序！！！"
        } else if (deviceRooted) {
            tv_version.text = "$version\n本设备已Root，存在一定风险！"
        } else {
            tv_version.text = version
        }
        val workVersionName = AppUtils.getAppInfo(Constant.PACKAGE_NAMES)?.versionName
        when (workVersionName) {
            null -> {
                LogUtils.e("系统检测到您尚未安装企业微信，请先安装企业微信")
                tv_work_version.text = "检测到您尚未安装企业微信，请先安装登录!"
            }
            in Constant.AVAILABLE_VERSION -> {
                LogUtils.i("当前企业微信版本已适配: $workVersionName")
                val tip = "$workVersionName   已适配，可放心使用~"
                tv_work_version.text = tip
                Constant.version = Constant.AVAILABLE_VERSION_MAP[workVersionName] ?: Int.MAX_VALUE
            }
            else -> {
                LogUtils.e("当前企业微信版本未兼容: $workVersionName")
                val tip = "$workVersionName   可能存在部分兼容性问题!"
                tv_work_version.text = tip
            }
        }
        LogUtils.i("Constant.version: ${Constant.version}")
        SPUtils.getInstance().put("appVersion", version)
        SPUtils.getInstance().put("workVersion", workVersionName)
        SPUtils.getInstance().put("deviceRooted", deviceRooted)
        SPUtils.getInstance().put("hook", hook)
    }

    private fun initAccessibility() {
        sw_accessibility.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            LogUtils.i("sw_accessibility onCheckedChanged: $isChecked")
            if (isChecked) {
                if (Constant.robotId.isBlank()) {
                    sw_accessibility.isChecked = false
                    ToastUtils.showLong("请先填写并保存链接号~")
                } else if (!PermissionHelper.isAccessibilitySettingOn()) {
                    if (SPUtils.getInstance().getBoolean("risk", false)) {
                        if (riskRetry > 10) {
                            ToastUtils.showLong("再点${20 - riskRetry}次 允许本次运行")
                        } else {
                            ToastUtils.showLong("环境监测异常，请勿使用本应用！")
                        }
                        if (++riskRetry > 20) {
                            SPUtils.getInstance().put("risk", false)
                            startActivity(Intent(this, AccessibilityGuideActivity::class.java))
                            ToastUtils.showLong("风险提示：临时允许本次运行")
                        }
                        sw_accessibility.isChecked = false
                    } else {
                        startActivity(Intent(this, AccessibilityGuideActivity::class.java))
                    }
                }
            } else {
                if (PermissionHelper.isAccessibilitySettingOn()) {
                    if (FlowPermissionHelper.isBlueCloud()) {
                        sw_accessibility.isChecked = true
                        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                        startActivity(intent)
                    } else {
                        try {
                            WeworkController.weworkService.disableSelf()
                        } catch (e: Exception) {
                            Log.e("TAG", "initAccessibility: " + e)
                        }
                    }
                }
            }
        })
    }

    private fun initOverlays() {
        sw_overlay.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            LogUtils.i("sw_overlay onCheckedChanged: $isChecked")
            if (isChecked) {
                startActivity(Intent(this, FloatViewGuideActivity::class.java))
            } else {
                if (Settings.canDrawOverlays(Utils.getApp()) && FlowPermissionHelper.canBackgroundStart(
                        Utils.getApp()
                    )
                ) {
                    sw_overlay.isChecked = true
                    PermissionPageManagement.goToSetting(this)
                }
            }
        })
        if (Settings.canDrawOverlays(Utils.getApp()) && FlowPermissionHelper.canBackgroundStart(
                Utils.getApp()
            )
        ) {
            FloatWindowHelper.showWindow()
        }
    }

    private fun initData() {
        HttpUtil.upgrade(this)

//        HttpUtil.getMyConfig(toast = false)
        CacheUtil.autoDelete()
    }

    private fun initNotification() {
        if (!Constant.enableMediaProject) {
            return
        }
        application.bindService(
            Intent(application, PlayNotifyService::class.java),
            object : ServiceConnection {
                override fun onServiceDisconnected(name: ComponentName) {
                    LogUtils.d("onServiceDisconnected")
                }

                override fun onServiceConnected(name: ComponentName, iBinder: IBinder) {
                    LogUtils.d("onServiceConnected")
                }
            },
            Context.BIND_AUTO_CREATE
        )
        //开启屏幕录制权限
        if (MediaProjectionHolder.mMediaProjection == null) {
            bt_save.postDelayed({
                fastStartActivity(this, GetScreenShotActivity::class.java)
            }, 1000)
        }
    }

    private fun showSelectHostDialog() {
        val hostList = SPUtils.getInstance().getStringSet("host_list", mutableSetOf(Constant.host))
        if (hostList.isNotEmpty()) {
            val hostArray = hostList.toTypedArray()
            QMUIDialog.CheckableDialogBuilder(this)
                .setTitle(getString(R.string.host_list))
                .addItems(hostArray) { dialog, which ->
                    Constant.host = hostArray[which]
                    tv_host.text = hostArray[which]
                    HostTestHelper.testWs()
                    dialog.dismiss()
                }
                .setCheckedIndex(hostList.indexOf(Constant.host))
                .create(R.style.QMUI_Dialog)
                .show()
        }
    }

    private fun showInputHostDialog() {
        ToastUtils.showLong("请输入专线网络")
        val builder = QMUIDialog.EditTextDialogBuilder(this)
        builder.setTitle(getString(R.string.tip))
            .setPlaceholder(getString(R.string.input_new_host))
            .setDefaultText(tv_host.text)
            .setInputType(InputType.TYPE_CLASS_TEXT)
            .addAction(getString(R.string.delete)) { dialog, index ->
                val hostList =
                    SPUtils.getInstance().getStringSet("host_list", mutableSetOf(Constant.host))
                if (hostList.size > 1) {
                    hostList.remove(Constant.host)
                    Constant.host = hostList.elementAt(0)
                    tv_host.text = Constant.host
                    HostTestHelper.testWs()
                    SPUtils.getInstance().put("host_list", hostList)
                    dialog.dismiss()
                } else {
                    ToastUtils.showLong("至少保留一个host！")
                }
            }
            .addAction(getString(R.string.cancel)) { dialog, index -> dialog.dismiss() }
            .addAction(getString(R.string.add)) { dialog, index ->
                val text = builder.editText.text
                if (text != null && text.isNotEmpty()) {
                    if (text.matches("ws{1,2}://[^/]+.*".toRegex())) {
                        val hostList = SPUtils.getInstance()
                            .getStringSet("host_list", mutableSetOf(Constant.host))
                        hostList.add(text.toString())
                        SPUtils.getInstance().put("host_list", hostList)
                        Constant.host = text.toString()
                        tv_host.text = text
                        HostTestHelper.testWs()
                        dialog.dismiss()
                    } else {
                        ToastUtils.showLong("格式异常！")
                    }
                } else {
                    ToastUtils.showLong("请勿为空！")
                }
            }
            .create(R.style.QMUI_Dialog).show()
    }

    private var needToWork = false

    private fun goToWork() {
        val positiveButton =
            MaterialAlertDialogBuilder(this, R.style.Theme_MaterialComponents_DayNight_Dialog)
                .setTitle("设置成功")
                .setMessage("请勿人工操作手机     \n5秒后自动跳转")
                .setNegativeButton("", null)
                .setPositiveButton("", null)
        val show = positiveButton.show()
        bt_save.postDelayed({ show.dismiss() }, 5000)
        bt_save.postDelayed({
            packageManager.getLaunchIntentForPackage(Constant.PACKAGE_NAMES)?.apply {
                this.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(this)
                if (weComNum() == 1) {
                    SPUtils.getInstance().put("weCom", 1)
                    SPUtils.getInstance().put("num", 1)
                    WeworkController.weworkService.webSocketManager.send(
                        WeworkMessageBean(
                            WeworkMessageBean.WE_COM_TYPE,
                            SPUtils.getInstance().getInt("weCom"),
                            SPUtils.getInstance().getInt("num"),
                            null
                        )
                    )
                } else {
                    bt_save.postDelayed({
                        val rootNode = WeworkController.weworkService.rootInActiveWindow
                        if (rootNode != null) {
                            // 查找并点击第一个应用
                            val firstAppNode: AccessibilityNodeInfo = findFirstAppNode(rootNode)!!
                            if (firstAppNode != null) {
                                AccessibilityUtil.performClick(firstAppNode)
                            }
                            SPUtils.getInstance().put("weCom", 1)
                            SPUtils.getInstance().put("num", 2)
//                        WeworkController.weworkService.webSocketManager.send(
//                                WeworkMessageListBean<Any?>(
//                                    1,
//                                    WeworkMessageListBean.SOCKET_TYPE_INTI
//                                )
//                            )
                            WeworkController.weworkService.webSocketManager.send(
                                WeworkMessageBean(
                                    WeworkMessageBean.WE_COM_TYPE,
                                    SPUtils.getInstance().getInt("weCom"),
                                    SPUtils.getInstance().getInt("num"),
                                    null
                                )
                            )
                        }
                    }, 500)
                }

            }
        }, 5000)
    }

    private val openWsReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.getStringExtra("type") == "openWs") {
                needToWork = intent.getBooleanExtra("switch", false)
            }
        }
    }

    var num: Int = 0

    fun weComNum(): Int {
//        val packageManager = packageManager
//        val installedApps = packageManager.getInstalledPackages(0)
//        val get = installedApps[178]
//        for (appInfo in installedApps) {
//            val packageName = appInfo.packageName
//            appInfo.applicationInfo.name
//                Log.e("aaaaa", "---------" + packageName)
//            // 可以进一步获取其他信息，如版本号、权限等
//        }

//        val packageManager = packageManager
//        val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
//        for (appInfo in apps) {
//            if (appInfo.packageName.contains("com.tencent.wework")) {
//                Log.e("AppInfo", "Installed app: " + appInfo.packageName)
//            }
//        }
        num = 0;
        val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val processes = activityManager.runningAppProcesses
        for (processInfo in processes) {
            if (processInfo.processName.contains("com.tencent.wework")) {
                Log.e("AppInfo", "Running app process: " + processInfo.processName)
                num++;
            }
        }
        return num
//        val packageManager = packageManager
//        val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
//        for (appInfo in apps) {
//            if (appInfo.packageName == "com.tencent.wework") {
//                // 找到主应用
//                Log.e("AppInfo", "Main app: " + appInfo.packageName)
//            } else if (appInfo.packageName.contains("com.tencent.wework:clone")) {
//                // 找到分身应用
//                Log.e("AppInfo", "Clone app: " + appInfo.packageName)
//            }
//        }


    }

    private fun findFirstAppNode(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        // 查找选择框中的第一个应用
//        val findAllByText = AccessibilityUtil.findAllByText(rootNode, "企业微信")
        val buttonList = AccessibilityUtil.findAllByClazz(rootNode, Views.ImageView)
        return buttonList.firstOrNull()
    }

    fun hasPermission(context: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
    }
}