// src/composables/useScreenStreams.js
import { ref, reactive, computed, watch } from 'vue'
import { tapAction, swipeAction } from '@/api/ios'

const BASE_W = 320
const BASE_H = 720
const THUMB_SCALE = 0.6
const PER_ROW = 3
const BOTTOM_SHIFT = Math.round(BASE_H * (1 - THUMB_SCALE)) // 288

export function useScreenStreams(deviceInformation) {
    // 选中的设备索引
    const selectedDevice = ref(null)

    // 每台设备的 <img> 引用
    const imgRefs = ref({})              // { [id]: HTMLImageElement }

    // 每台设备当前展示的 URL
    const imgSrcMap = reactive({})       // { [deviceId]: string }

    // 每台设备循环状态
    const loops = new Map()              // deviceId -> { timer, stopped }

    // const makeUrl = (port) => `http://192.168.1.218:${port}/?t=${Date.now()}`
    const makeUrl = (port) => `http://localhost:${port}/?t=${Date.now()}`

    function hardCloseImg(deviceId) {
        const el = imgRefs.value[deviceId]
        if (el) {
            el.src = ''
            el.removeAttribute('src')
        }
        imgSrcMap[deviceId] = ''
    }

    function stopLoop(deviceId) {
        const s = loops.get(deviceId)
        if (!s) {
            hardCloseImg(deviceId)
            return
        }
        s.stopped = true
        if (s.timer) clearTimeout(s.timer)
        loops.delete(deviceId)
        hardCloseImg(deviceId)
    }

    function startLoop(dev, idx = 0) {
        stopLoop(dev.deviceId)
        const state = { timer: null, stopped: false }
        loops.set(dev.deviceId, state)

        const tick = () => {
            if (state.stopped) return
            const url = makeUrl(dev.screenPort)
            imgSrcMap[dev.deviceId] = url
            state.timer = window.setTimeout(tick, 3000)
        }

        state.timer = window.setTimeout(tick, idx * 200)
    }

    function reconcileLoopsByDevices(list) {
        const keep = new Set(list.map(d => d.deviceId))

        // 停掉没了的设备
        for (const id of Array.from(loops.keys())) {
            if (!keep.has(id)) stopLoop(id)
        }
        // 为新增设备启动循环
        list.forEach((d, i) => {
            if (!loops.has(d.deviceId)) startLoop(d, i)
        })
    }

    function refreshOneImg(deviceId) {
        const dev = deviceInformation.value.find(d => d.deviceId === deviceId)
        if (dev) {
            stopLoop(deviceId)
            startLoop(dev, 0)
        }
    }

    function refreshAllImgs() {
        deviceInformation.value.forEach((d, i) => {
            stopLoop(d.deviceId)
            startLoop(d, i)
        })
    }

    function refreshAllStopImgs() {
        Object.keys(imgRefs.value).forEach(id => hardCloseImg(id))
    }

    // 设备变动时自动对齐循环
    watch(deviceInformation, (list) => {
        reconcileLoopsByDevices(list || [])
    }, { deep: true })

    // ——— 选中 + 缩放/上移样式 ———
    const hasTwoRows = computed(() => deviceInformation.value.length > PER_ROW)

    const isBottomRow = (index) => {
        if (!hasTwoRows.value) return false
        const lastRow = Math.floor((deviceInformation.value.length - 1) / PER_ROW)
        return Math.floor(index / PER_ROW) === lastRow
    }

    function getCanvasStyle(index) {
        const isSelected = selectedDevice.value === index
        if (!isSelected) {
            return { transform: `scale(${THUMB_SCALE})` }
        }
        return isBottomRow(index)
            ? { transform: `translateY(-${BOTTOM_SHIFT}px) scale(1)` }
            : { transform: 'scale(1)' }
    }

    const imgWH = (index) => {
        const scale = (selectedDevice.value === index) ? 1 : THUMB_SCALE
        return {
            width: `${BASE_W * scale}px`,
            height: `${BASE_H * scale}px`,
            transition: 'all 0.3s ease',
        }
    }

    const displaySize = (index) => {
        const scale = (selectedDevice.value === index) ? 1 : THUMB_SCALE
        return { w: BASE_W * scale, h: BASE_H * scale }
    }

    const selectDevice = (index) => {
        selectedDevice.value = index
    }

    // ——— 坐标映射 + 鼠标交互 ———
    const dragState = ref({}) // index -> { ox, oy, t, udid, ... }

    const mapToDeviceXY = (index, offsetX, offsetY) => {
        const dev = deviceInformation.value[index] || {}
        const realW = Number(dev.width) || BASE_W
        const realH = Number(dev.height) || BASE_H
        const rotation = Number(dev.rotation || 0)

        const { w: dispW, h: dispH } = displaySize(index)
        let nx = Math.min(Math.max(offsetX / dispW, 0), 1)
        let ny = Math.min(Math.max(offsetY / dispH, 0), 1)

        let x, y
        switch (rotation % 360) {
            case 90:
            case -270:
                x = Math.round(ny * realW)
                y = Math.round((1 - nx) * realH)
                break
            case 180:
            case -180:
                x = Math.round((1 - nx) * realW)
                y = Math.round((1 - ny) * realH)
                break
            case 270:
            case -90:
                x = Math.round((1 - ny) * realW)
                y = Math.round(nx * realH)
                break
            default:
                x = Math.round(nx * realW)
                y = Math.round(ny * realH)
        }
        return { x, y }
    }

    const onCanvasDown = (udid, e, index) => {
        const startDev = mapToDeviceXY(index, e.offsetX, e.offsetY)
        dragState.value[index] = {
            ox: e.offsetX,
            oy: e.offsetY,
            t: Date.now(),
            udid,
            startDevXY: startDev,
            startOffsetXY: { x: e.offsetX, y: e.offsetY }
        }
    }

    const onCanvasMove = (udid, e, index) => {
        const st = dragState.value[index]
        if (!st) return
        // const curDev = mapToDeviceXY(index, e.offsetX, e.offsetY)
        // 调试需要再打印
    }

    const onCanvasUp = async (udid, e, index) => {
        const st = dragState.value[index]
        if (!st) return

        const { ox, oy, t, startDevXY, startOffsetXY } = st
        const dx = e.offsetX - ox
        const dy = e.offsetY - oy
        const elapsed = Date.now() - t
        delete dragState.value[index]

        const endDevXY = mapToDeviceXY(index, e.offsetX, e.offsetY)
        const endOffsetXY = { x: e.offsetX, y: e.offsetY }

        console.log('[鼠标滑动，起点/终点）+ 耗时]', {
            udid,
            start: {
                offsetXY: startOffsetXY,
                deviceXY: startDevXY
            },
            end: {
                offsetXY: endOffsetXY,
                deviceXY: endDevXY
            },
            deltaOffset: { dx, dy },
            durationMs: elapsed,
        })

        const MOVE_THR = 5
        const isTap = Math.hypot(dx, dy) < MOVE_THR && elapsed < 500

        try {
            if (isTap) {
                await tapAction({ udid, x: endDevXY.x, y: endDevXY.y })
            } else {
                await swipeAction({
                    udid,
                    sx: startDevXY.x,
                    sy: startDevXY.y,
                    ex: endDevXY.x,
                    ey: endDevXY.y,
                    duration: elapsed / 1000
                })
            }
        } catch (err) {
            console.error(err)
        }
    }

    return {
        selectedDevice,
        imgRefs,
        imgSrcMap,
        refreshAllImgs,
        refreshOneImg,
        refreshAllStopImgs,
        getCanvasStyle,
        imgWH,
        selectDevice,
        onCanvasDown,
        onCanvasMove,
        onCanvasUp,
    }
}
