import browser from "/@/utils/browser";
import axios from "axios";
import { ref, computed, unref } from 'vue'

const roomParam = browser.getURLParam("roomId")

interface roomDataType {
    sceneData: any[]
}

export const room = ref<Nullable<roomDataType>>(null)
export const roomId = roomParam && roomParam.substr(7)
export const sceneList = computed(() => unref(room)?.sceneData || [])
export const isLeader = browser.getURLParam("role") === 'leader'


export function useRoom() {
    return {
        sceneList,
        currentScene,
        changeScene,
        initialRoom,
        enterRoom,
    }
}

export const currentScene = computed(() => {
    const num = browser.getURLParam("m")
    return sceneList.value.find(scene => scene.num === num)
})

export const changeScene = (scene) => {
    if (currentScene.value?.num !== scene.num) {
        console.log(scene, currentScene.value)
        const params = new URLSearchParams(location.search)
        params.set('m', scene.num)
        const url = new URL(location.href)
        url.search = `?` + params.toString()
        location.replace(url)
    }
}


const shopAxios = axios.create({ baseURL: !import.meta.env.DEV ? 'https://v4-test.4dkankan.com' : '' })

export const initialRoom = async () => {
    const res = await shopAxios.get('/takelook/roomInfo', { params: { roomId } })
    room.value = res.data.data
    console.log(room.value)
}

export const enterRoom = async () => {
    if (!isLeader) return;
    await shopAxios.get('/takelook/inOrOutRoom', {
        params: {
            type: 0,
            role: 'leader',
            roomId
        }
    })
}

export const leaveRoom = async () => {
    if (!isLeader) return;
    await shopAxios.get('/takelook/inOrOutRoom', {
        params: {
            type: 1,
            role: 'leader',
            roomId
        }
    })
}

if (roomId) {
    shopAxios.get('/takelook/roomAddView', { params: { roomId } })
}