package com.stand.standapp

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Process
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.stand.standapp.printer.PrinterManager
import okhttp3.*
import org.json.JSONObject
import timber.log.Timber
import java.io.IOException

class LoginActivity : AppCompatActivity() {

    private val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        // 新安装时直接申请录音权限
        XXPermissions.with(this)
            .permission(Permission.RECORD_AUDIO)
            .request(null)

        val etUsername = findViewById<EditText>(R.id.et_username)
        val etPassword = findViewById<EditText>(R.id.et_password)
        val cbRemember = findViewById<CheckBox>(R.id.cb_remember)
        val btnLogin = findViewById<Button>(R.id.btn_login)
        val btnLoginOfficial = findViewById<Button>(R.id.btn_login_official)
        val btnExit = findViewById<Button>(R.id.btn_exit)
        val ivSettings = findViewById<ImageView>(R.id.iv_settings)
        val tvCopyright = findViewById<TextView>(R.id.tv_copyright)

        // 1. 加载保存的状态和凭据
        val isRemember = AppConfig.isRememberLogin(this)
        cbRemember.isChecked = isRemember
        if (isRemember) {
            etUsername.setText(AppConfig.getSavedUsername(this))
            etPassword.setText(AppConfig.getSavedPassword(this))
        }

        // 2. 服务器配置图标点击事件
        ivSettings.setOnClickListener {
            showServerConfigDialog()
        }

        // 3. 登录按钮点击事件
        btnLogin.setOnClickListener {
            val username = etUsername.text.toString().trim()
            val password = etPassword.text.toString().trim()

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(applicationContext, "请输入账号和密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 执行真实接口登录
            performLogin(username, password, cbRemember.isChecked, false)
        }

        // 3.1 正式界面登录按钮点击事件
        btnLoginOfficial.setOnClickListener {
            val username = etUsername.text.toString().trim()
            val password = etPassword.text.toString().trim()

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(applicationContext, "请输入账号和密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            performLogin(username, password, cbRemember.isChecked, true)
        }

        // 4. 退出按钮
        btnExit.setOnClickListener {
            com.stand.standapp.utils.AppKiller.killApp(this)
        }

        // 5. 彩蛋：点击底部版权 10 次进入开发者模式
        var clickCount = 0
        var lastClickTime = 0L
        tvCopyright.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            // 连续点击判定间隔为 500ms
            if (currentTime - lastClickTime < 500) {
                clickCount++
            } else {
                clickCount = 1
            }
            lastClickTime = currentTime

            if (clickCount >= 10) {
                clickCount = 0
                Toast.makeText(applicationContext, "开发者模式已激活", Toast.LENGTH_SHORT).show()
                startActivity(Intent(this, DeveloperActivity::class.java))
            } else if (clickCount > 5) {
                Toast.makeText(applicationContext, "再点击 ${10 - clickCount} 次进入调试模式", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun performLogin(username: String, password: String, remember: Boolean, officialMode: Boolean) {
        Timber.tag("Login").d("开始登录: username=%s, server=%s", username, AppConfig.getServerUrl(this))
        val serverUrl = AppConfig.getServerUrl(this)
        val loginUrl = "$serverUrl/api/auth/login"
        
        val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", username)
            .addFormDataPart("password", password)
            .build()

        val request = Request.Builder()
            .url(loginUrl)
            .post(body)
            .build()

        val loadingDialog = AlertDialog.Builder(this)
            .setMessage("正在登录...")
            .setCancelable(false)
            .create()
        loadingDialog.show()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Timber.tag("Login").e(e, "登录网络请求失败")
                runOnUiThread {
                    loadingDialog.dismiss()
                    Toast.makeText(applicationContext, "网络异常: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onResponse(call: Call, response: Response) {
                val responseBody = response.body?.string()
                runOnUiThread {
                    loadingDialog.dismiss()
                    try {
                        val json = JSONObject(responseBody ?: "")
                        val code = json.optInt("code", -1)
                        if (code == 0) {
                            AppConfig.setRememberLogin(this@LoginActivity, remember)
                            if (remember) {
                                AppConfig.setSavedUsername(this@LoginActivity, username)
                                AppConfig.setSavedPassword(this@LoginActivity, password)
                            } else {
                                AppConfig.setSavedUsername(this@LoginActivity, "")
                                AppConfig.setSavedPassword(this@LoginActivity, "")
                            }

                            // 提取登录数据
                            val data = json.optJSONObject("data")
                            val loginData = data?.toString() ?: "{}"
                            val accessToken = data?.optString("access_token", "") ?: ""
                            AppConfig.setAccessToken(this@LoginActivity, accessToken)

                            Toast.makeText(applicationContext, "登录成功", Toast.LENGTH_SHORT).show()

                            // 获取独立的 PTT 账号并初始化
                            Timber.tag("PTT").d("开始PTT初始化流程: username=%s, hasToken=%b", username, accessToken.isNotEmpty())
                            initPttWithAccount(username, accessToken)

                            // 2. 启动硬件 GPIO 监听
                            try {
                                com.stand.standapp.utils.GpioManager.init(this@LoginActivity)
                                com.stand.standapp.utils.GpioManager.startListening()
                                Timber.tag("GPIO").d("GPIO初始化并启动监听成功")
                            } catch (e: Exception) {
                                Timber.tag("GPIO").e(e, "GPIO init error")
                            }

                            // 3. 初始化打印机 (异步)
                            PrinterManager.init(this@LoginActivity)

                            // 4. 检查是否有临时群组，有则打开临时呼叫页面
                            checkTempGroup(username, data)

                            // 5. 启动 MainActivity，传递登录模式和数据
                            val intent = Intent(this@LoginActivity, MainActivity::class.java)
                            intent.putExtra("official_mode", officialMode)
                            intent.putExtra("login_data", loginData)
                            startActivity(intent)
                            finish()
                        } else {
                            val msg = json.optString("msg", "登录失败")
                            Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
                        }

                    } catch (e: Exception) {
                        Timber.tag("Login").e(e, "解析响应失败")
                        Toast.makeText(applicationContext, "服务器响应异常", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    private fun showServerConfigDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_settings, null)
        val etServerUrl = dialogView.findViewById<EditText>(R.id.et_server_url)
        val etSerialPort = dialogView.findViewById<EditText>(R.id.et_serial_port)
        val btnReset = dialogView.findViewById<TextView>(R.id.btn_reset)

        etServerUrl.setText(AppConfig.getServerUrl(this))
        etSerialPort.setText(AppConfig.getSerialPort(this))

        val dialog = AlertDialog.Builder(this, R.style.CustomDialogTheme)
            .setView(dialogView)
            .setCancelable(false)
            .create()

        btnReset.setOnClickListener {
            etServerUrl.setText(AppConfig.DEFAULT_SERVER_URL)
            etSerialPort.setText(AppConfig.DEFAULT_SERIAL_PORT)
            Toast.makeText(applicationContext, "已重置数值 (待保存)", Toast.LENGTH_SHORT).show()
        }

        dialogView.findViewById<TextView>(R.id.btn_cancel).setOnClickListener {
            dialog.dismiss()
        }

        dialogView.findViewById<TextView>(R.id.btn_save).setOnClickListener {
            val serverUrl = etServerUrl.text.toString().trim()
            val serialPort = etSerialPort.text.toString().trim()
            
            if (serverUrl.isEmpty()) {
                etServerUrl.error = "地址不能为空"
                return@setOnClickListener
            }

            AppConfig.setServerUrl(this, serverUrl)
            AppConfig.setSerialPort(this, serialPort)
            
            Toast.makeText(applicationContext, "参数已生效", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }

        dialog.show()

        dialog.window?.let { window ->
            val params = window.attributes
            params.width = (resources.displayMetrics.widthPixels * 0.95).toInt()
            window.attributes = params
        }
    }

    override fun onBackPressed() {
        AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage("确定要退出应用吗？")
            .setPositiveButton("确定") { _, _ ->
                com.stand.standapp.utils.AppKiller.killApp(this)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun checkTempGroup(account: String, loginData: org.json.JSONObject?) {
        val accessToken = loginData?.optString("access_token", "") ?: return
        if (accessToken.isEmpty()) return

        val serverUrl = AppConfig.getServerUrl(this)
        val url = "$serverUrl/api/external/ptt/user/groups?account=$account"

        val request = Request.Builder()
            .url(url)
            .addHeader("Authorization", "Bearer $accessToken")
            .get()
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Timber.tag("TempGroup").w(e, "检查临时群组失败")
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    val body = response.body?.string() ?: return
                    val json = JSONObject(body)
                    val dataObj = json.optJSONObject("data")
                    val list = dataObj?.optJSONArray("data") ?: return

                    for (i in 0 until list.length()) {
                        val group = list.optJSONObject(i) ?: continue
                        val gtype = group.optString("gtype", "")
                        if (gtype == "2") {
                            val gname = group.optString("gname", "临时群组")
                            Timber.tag("TempGroup").d("发现临时群组: $gname")
                            // 打开临时呼叫页面
                            val appCtx = com.stand.standapp.MyApplication.getAppInstance()
                            val intent = android.content.Intent(
                                appCtx,
                                TempCallActivity::class.java
                            )
                            intent.putExtra("group_name", gname)
                            intent.addFlags(
                                android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
                                android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK or
                                android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                            )
                            appCtx.startActivity(intent)
                            break
                        }
                    }
                } catch (e: Exception) {
                    Timber.tag("TempGroup").e(e, "解析临时群组响应失败")
                }
            }
        })
    }

    private fun initPttWithAccount(username: String, accessToken: String) {
        if (accessToken.isEmpty()) {
            Timber.tag("PTT").w("accessToken为空，使用默认PTT密码: username=%s", username)
            doPttInit(username, "123456")
            return
        }

        val serverUrl = AppConfig.getServerUrl(this)
        val url = "$serverUrl/api/poc-card/account/$username"

        val request = Request.Builder()
            .url(url)
            .addHeader("Authorization", "Bearer $accessToken")
            .get()
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Timber.tag("PTT").w(e, "获取 PTT 账号失败，使用默认账号")
                doPttInit(username, "123456")
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    val body = response.body?.string() ?: ""
                    val json = JSONObject(body)
                    if (json.optInt("code") == 0) {
                        val data = json.optJSONObject("data")
                        val pttUsername = data?.optString("cardNumber", username) ?: username
                        val pttPassword = data?.optString("pocPassword", "123456") ?: "123456"
                        Timber.tag("PTT").d("获取到服务器PTT账号: cardNumber=%s", pttUsername)
                        doPttInit(pttUsername, pttPassword)
                    } else {
                        Timber.tag("PTT").w("获取PTT账号失败, code=%d", json.optInt("code"))
                        doPttInit(username, "123456")
                    }
                } catch (e: Exception) {
                    Timber.tag("PTT").e(e, "解析 PTT 账号失败")
                    doPttInit(username, "123456")
                }
            }
        })
    }

    private fun doPttInit(pttUsername: String, pttPassword: String) {
        Timber.tag("PTT").d("PTT初始化开始: username=%s", pttUsername)
        android.os.Handler(android.os.Looper.getMainLooper()).post {
            Toast.makeText(applicationContext, "PTT初始化中...", Toast.LENGTH_SHORT).show()
        }

        // 1. PTT 引擎强制重置后登录 (销毁旧 session，确保干净状态)
        try {
            Timber.tag("PTT").d("发送PTT取消登录指令")
            com.example.kingway.ptt.SendAtUtil.toCancelLogin()
            Timber.tag("PTT").d("发送PTT注销指令")
            com.example.kingway.ptt.SendAtUtil.toLogout()
        } catch (e: Exception) {
            Timber.tag("PTT").e(e, "PTT init error")
        }

        // 使用 Handler 替代硬编码 Thread.sleep，避免阻塞或随意开辟线程
        Timber.tag("PTT").d("等待1500ms以确保旧session完全清理")
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            try {
                Timber.tag("PTT").d("发送PTT登录指令: username=%s, ip=%s", pttUsername, "220.154.131.231")
                com.example.kingway.ptt.SendAtUtil.toLogin(pttUsername, pttPassword, "220.154.131.231", 1, 1)
            } catch (e: Exception) {
                Timber.tag("PTT").e(e, "PTT login error")
            }
        }, 1500)
    }
}
