// src/composables/useDevices.js
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getDeviceList,
    stopScript,
    deviceAppList,
    launchApp,
} from '@/api/ios'
import { pickTikTokBundleId } from '@/utils/arrUtils'

export function useDevices() {
    const deviceInformation = ref([])      // 设备列表
    const getListTimer = ref(null)        // 定时器句柄（方便在外面清理）

    // 是否已经提示过 IOSAI 服务错误
    let isStartLac = false

    // 拉设备列表
    const getDeviceListFun = async () => {
        try {
            const res = await getDeviceList()
            if (res && res.length > 0 && deviceInformation.value.length !== res.length) {
                console.log('设备变更')
                deviceInformation.value = res
            }
            if (!res || res.length === 0) {
                deviceInformation.value = []
            }
        } catch (err) {
            if (isStartLac) {
                ElMessage.error('IOSAI 服务错误')
            } else {
                // 第一次忽略，等下次再报（保持你原来的行为）
                isStartLac = true
            }
        }
    }

    // 打开 Tiktok
    const openTk = async () => {
        if (!deviceInformation.value?.length) {
            ElMessage.warning('暂无在线设备')
            return
        }

        const { ElLoading } = await import('element-plus')
        const loading = ElLoading.service({
            text: '正在打开 TikTok …',
            background: 'rgba(0,0,0,.35)'
        })

        const results = []

        try {
            for (const dev of deviceInformation.value) {
                const udid = dev.deviceId
                try {
                    const apps = await deviceAppList({ udid })
                    const bundleId = pickTikTokBundleId(apps)

                    if (!bundleId) {
                        results.push({ udid, ok: false, msg: '未找到 TikTok' })
                        continue
                    }

                    await launchApp({ udid, bundleId })
                    results.push({ udid, ok: true, msg: `已启动 TikTok (${bundleId})` })
                } catch (e) {
                    console.error('openTk error', udid, e)
                    results.push({ udid, ok: false, msg: '请求失败' })
                }
            }
        } finally {
            loading.close()
        }

        const okCount = results.filter(r => r.ok).length
        const fail = results.filter(r => !r.ok)
        if (okCount) ElMessage.success(`已在 ${okCount} 台设备启动 TikTok`)
        if (fail.length) {
            const udids = fail.map(f => f.udid).join(', ')
            ElMessage.error(`以下设备未能启动：${udids}`)
        }
    }

    // 停止单台任务
    const stopOne = async (deviceId) => {
        try {
            await stopScript({ udid: deviceId })
            // 你原来这里没有提示，我也保持不弹
            // ElMessage.success('停止成功')
        } catch (e) {
            console.error('stopOne error', e)
        }
    }

    return {
        deviceInformation,
        getDeviceListFun,
        getListTimer,
        openTk,
        stopOne,
    }
}
