// service/PhoneCallService.kt
package com.example.initiateaphonecallapp.service

import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaRecorder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import androidx.core.content.ContextCompat
import com.example.initiateaphonecallapp.manager.CallRecordManager
import java.io.File
import java.util.*

class PhoneCallService : Service() {
    private var isInitialized = false
    private var telephonyManager: TelephonyManager? = null
    private var phoneStateListener: PhoneStateListener? = null
    private var mediaRecorder: MediaRecorder? = null
    private var recordingPath: String? = null
    private var isRecording = false

    // 自动拨号相关变量
    private var isAutoDialing = false
    private var currentDialIndex = 0
    private var pipelineList: List<com.example.initiateaphonecallapp.data.model.PipelineResponse> = emptyList()
    private val handler = Handler(Looper.getMainLooper())
    private var autoDialRunnable: Runnable? = null
    private var isCallInProgress = false
    private var lastCallState = TelephonyManager.CALL_STATE_IDLE

    companion object {
        private const val TAG = "PhoneCallService"
        private const val AUTO_DIAL_INTERVAL = 10000L // 10秒
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "✅ onCreate() 被调用")
        telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
        initializePhoneListener()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "✅ onStartCommand() 被调用")

        // 确保电话监听器已初始化
        if (!isInitialized) {
            initializePhoneListener()
        }

        intent?.let { receivedIntent ->
            when (receivedIntent.action) {
                "ACTION_INITIATE_CALL" -> {
                    val phoneNumber = receivedIntent.getStringExtra("PHONE_NUMBER")
                    val pipelineId = receivedIntent.getStringExtra("PIPELINE_ID")
                    Log.d(TAG, "📞 收到拨号请求，号码: $phoneNumber, 管道ID: $pipelineId")
                    phoneNumber?.let { number ->
                        initiateCall(number, pipelineId)
                    }
                }
                "ACTION_START_AUTO_DIAL" -> {
                    val pipelines = receivedIntent.getSerializableExtra("PIPELINE_LIST") as? ArrayList<com.example.initiateaphonecallapp.data.model.PipelineResponse>
                    pipelines?.let { list ->
                        startAutoDial(list)
                    } ?: run {
                        Log.e(TAG, "❌ 自动拨号启动失败：没有管道列表")
                    }
                }
                "ACTION_STOP_AUTO_DIAL" -> {
                    stopAutoDial()
                }
                // 新增：从指定位置开始自动拨号
                "ACTION_START_AUTO_DIAL_FROM_CURRENT" -> {
                    val pipelines = receivedIntent.getSerializableExtra("PIPELINE_LIST") as? ArrayList<com.example.initiateaphonecallapp.data.model.PipelineResponse>
                    val startIndex = receivedIntent.getIntExtra("START_INDEX", 0)
                    pipelines?.let { list ->
                        startAutoDialFromCurrent(list, startIndex)
                    } ?: run {
                        Log.e(TAG, "❌ 从指定位置自动拨号启动失败：没有管道列表")
                    }
                }
                // 新增：更新自动拨号索引
                "ACTION_UPDATE_DIAL_INDEX" -> {
                    val pipelines = receivedIntent.getSerializableExtra("PIPELINE_LIST") as? ArrayList<com.example.initiateaphonecallapp.data.model.PipelineResponse>
                    val currentIndex = receivedIntent.getIntExtra("CURRENT_INDEX", 0)
                    pipelines?.let { list ->
                        updateAutoDialIndex(list, currentIndex)
                    } ?: run {
                        Log.e(TAG, "❌ 更新自动拨号索引失败：没有管道列表")
                    }
                }
                else -> {}
            }
        }

        return START_REDELIVER_INTENT
    }

    private fun initializePhoneListener() {
        if (!hasPhoneStatePermission()) {
            Log.e(TAG, "❌ 没有权限设置电话状态监听器")
            return
        }

        if (isInitialized) {
            return
        }

        try {
            phoneStateListener = object : PhoneStateListener() {
                override fun onCallStateChanged(state: Int, phoneNumber: String?) {
                    Log.d(TAG, "📞 电话状态变化: $state, 号码: $phoneNumber, 上次状态: $lastCallState")

                    when (state) {
                        TelephonyManager.CALL_STATE_RINGING -> {
                            Log.d(TAG, "📳 来电状态: $phoneNumber")
                            isCallInProgress = false
                            lastCallState = state
                        }
                        TelephonyManager.CALL_STATE_OFFHOOK -> {
                            // 通话开始
                            Log.d(TAG, "📞 通话开始")
                            isCallInProgress = true
                            lastCallState = state
                            // 通知 CallRecordManager 通话已连接
                            CallRecordManager.updateCallToConnected()
                        }
                        TelephonyManager.CALL_STATE_IDLE -> {
                            // 通话结束 - 只有当之前是通话中时才处理
                            if (lastCallState == TelephonyManager.CALL_STATE_OFFHOOK) {
                                Log.d(TAG, "📴 通话结束")
                                isCallInProgress = false
                                // 通知 CallRecordManager 通话结束
                                CallRecordManager.endCallRecord()

                                // 如果正在自动拨号，通话结束后10秒拨打下一个
                                if (isAutoDialing) {
                                    Log.d(TAG, "⏰ 通话结束，10秒后拨打下一个")
                                    handler.postDelayed({
                                        dialNextNumber()
                                    }, AUTO_DIAL_INTERVAL)
                                }
                            } else {
                                Log.d(TAG, "📴 空闲状态（未从通话中转换）")
                            }
                            lastCallState = state
                        }
                    }
                }
            }

            // 注册电话状态监听器
            telephonyManager?.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
            isInitialized = true
            Log.d(TAG, "✅ 电话状态监听器初始化成功")

        } catch (e: SecurityException) {
            Log.e(TAG, "❌ 电话状态监听器初始化失败 - 权限问题: ${e.message}")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 电话状态监听器初始化失败: ${e.message}")
        }
    }

    private fun hasPhoneStatePermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.READ_PHONE_STATE
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun hasRecordAudioPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun initiateCall(phoneNumber: String, pipelineId: String? = null): Boolean {
        if (!hasPhoneStatePermission()) {
            Log.e(TAG, "❌ 没有权限拨打电话")
            CallRecordManager.markCallAsFailed("缺少电话权限")
            return false
        }

        // 重置通话状态
        isCallInProgress = false
        lastCallState = TelephonyManager.CALL_STATE_IDLE

        // 通知 CallRecordManager 开始通话记录
        CallRecordManager.startCallRecord(phoneNumber)

        // 拨打电话
        val intent = Intent(Intent.ACTION_CALL).apply {
            data = android.net.Uri.parse("tel:$phoneNumber")
        }
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        return try {
            startActivity(intent)
            Log.d(TAG, "✅ 拨号成功: $phoneNumber")
            true
        } catch (e: SecurityException) {
            Log.e(TAG, "❌ 拨号失败，缺少 CALL_PHONE 权限: ${e.message}")
            CallRecordManager.markCallAsFailed("缺少拨号权限: ${e.message}")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 拨号失败: ${e.message}")
            CallRecordManager.markCallAsFailed("拨号失败: ${e.message}")
            false
        }
    }

    // 自动拨号功能
    private fun startAutoDial(pipelines: List<com.example.initiateaphonecallapp.data.model.PipelineResponse>) {
        if (pipelines.isEmpty()) {
            Log.e(TAG, "❌ 自动拨号启动失败：管道列表为空")
            return
        }

        if (isAutoDialing) {
            Log.w(TAG, "⚠️ 自动拨号已经在运行中")
            return
        }

        isAutoDialing = true
        pipelineList = pipelines
        currentDialIndex = 0

        Log.d(TAG, "🚀 开始自动拨号，共 ${pipelineList.size} 个号码")

        // 重置通话状态
        isCallInProgress = false
        lastCallState = TelephonyManager.CALL_STATE_IDLE

        // 开始第一个拨号
        dialNextNumber()
    }

    // 新增：从指定位置开始自动拨号
    private fun startAutoDialFromCurrent(pipelines: List<com.example.initiateaphonecallapp.data.model.PipelineResponse>, startIndex: Int) {
        if (pipelines.isEmpty()) {
            Log.e(TAG, "❌ 从指定位置自动拨号启动失败：管道列表为空")
            return
        }

        // 如果已经在自动拨号，先停止
        if (isAutoDialing) {
            stopAutoDial()
        }

        isAutoDialing = true
        pipelineList = pipelines
        currentDialIndex = startIndex

        Log.d(TAG, "🚀 从位置 $startIndex 开始自动拨号，共 ${pipelineList.size} 个号码")

        // 重置通话状态
        isCallInProgress = false
        lastCallState = TelephonyManager.CALL_STATE_IDLE

        // 从指定位置开始拨号
        dialNextNumber()
    }

    // 新增：更新自动拨号索引
    private fun updateAutoDialIndex(pipelines: List<com.example.initiateaphonecallapp.data.model.PipelineResponse>, currentIndex: Int) {
        if (!isAutoDialing) {
            Log.w(TAG, "⚠️ 自动拨号未运行，无法更新索引")
            return
        }

        if (currentIndex < 0 || currentIndex >= pipelineList.size) {
            Log.e(TAG, "❌ 更新自动拨号索引失败：索引 $currentIndex 超出范围")
            return
        }

        // 更新管道列表和当前索引
        pipelineList = pipelines
        currentDialIndex = currentIndex

        Log.d(TAG, "🔄 更新自动拨号索引为: $currentIndex")

        // 取消当前的等待
        autoDialRunnable?.let { handler.removeCallbacks(it) }

        // 如果当前没有通话中，立即拨打新的号码
        if (!isCallInProgress) {
            dialNextNumber()
        }
        // 如果正在通话中，等待通话结束后会自动拨打新的索引位置的号码
    }

    private fun stopAutoDial() {
        if (!isAutoDialing) {
            Log.w(TAG, "⚠️ 自动拨号未运行")
            return
        }

        isAutoDialing = false
        autoDialRunnable?.let { handler.removeCallbacks(it) }
        pipelineList = emptyList()
        currentDialIndex = 0
        isCallInProgress = false
        lastCallState = TelephonyManager.CALL_STATE_IDLE

        Log.d(TAG, "🛑 自动拨号已停止")

        // 发送广播通知UI自动拨号已停止
        sendBroadcast(Intent("AUTO_DIAL_STOPPED"))
    }

    private fun dialNextNumber() {
        if (!isAutoDialing) {
            return
        }

        // 检查是否所有号码都已拨打
        if (currentDialIndex >= pipelineList.size) {
            Log.d(TAG, "🎉 所有号码拨打完成")
            stopAutoDial()
            return
        }

        // 如果当前正在通话中，等待通话结束
        if (isCallInProgress) {
            Log.d(TAG, "⏳ 当前正在通话中，等待通话结束后继续")
            return
        }

        val pipeline = pipelineList[currentDialIndex]

        // 检查状态：只有status为0或1才拨打
        if (pipeline.status != 0 && pipeline.status != 1) {
            Log.d(TAG, "⏭️ 跳过状态为 ${pipeline.status} 的客户: ${pipeline.name}")
            currentDialIndex++
            // 立即拨打下一个，不等待
            handler.post {
                dialNextNumber()
            }
            return
        }

        Log.d(TAG, "📞 自动拨打第 ${currentDialIndex + 1} 个号码: ${pipeline.name} - ${pipeline.phone} (状态: ${pipeline.status})")

        // 通知UI当前拨打的索引
        sendBroadcast(Intent("AUTO_DIAL_NEXT").apply {
            putExtra("current_index", currentDialIndex)
        })

        val success = initiateCall(pipeline.phone, pipeline.id)

        if (success) {
            currentDialIndex++
            // 如果拨打成功，等待通话结束（通话结束后会自动拨打下一个）
        } else {
            // 如果拨打失败，10秒后尝试下一个
            Log.w(TAG, "❌ 拨打失败，10秒后尝试下一个")
            currentDialIndex++
            handler.postDelayed({
                dialNextNumber()
            }, AUTO_DIAL_INTERVAL)
        }
    }

    override fun onDestroy() {
        Log.d(TAG, "🔚 onDestroy()")
        stopAutoDial()

        // 正确取消注册电话状态监听器
        try {
            phoneStateListener?.let { listener ->
                telephonyManager?.listen(listener, PhoneStateListener.LISTEN_NONE)
            }
            phoneStateListener = null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 取消注册电话状态监听器失败: ${e.message}")
        }

        telephonyManager = null
        isInitialized = false
        super.onDestroy()
    }
}