<template>
    <main>
        <iframe ref="sourceFrame" v-if="sourceURL" :src="sourceURL" frameborder="0" @load="onLoadSource"></iframe>
        <div class="model" v-show="!showAdjust">
            <div class="bim" :class="{ active: bimChecked, disable: project && !project.bimData }">
                <div @click="onBimChecked">
                    <i class="iconfont icon-BIM"></i>
                </div>
                <span v-show="showBimTips">BIM</span>
            </div>
        </div>
        <div class="tools"  v-if="source" v-show="!bimChecked">
            <div class="item-date">
                <Calendar :value="sourceDate" :highlighted="sourceDays" @selected="onSelected" @prev="onPrevDate" @next="onNextDate" />
            </div>
            <div class="item-mode" v-if="source.type == 2">
                <div class="iconfont icon-show_roaming" :class="{ active: mode == 0 }" @click="onModeChange(0)"></div>
                <div class="iconfont icon-show_plane" :class="{ active: mode == 1 }" @click="onModeChange(1)"></div>
            </div>
        </div>
    </main>
    <Toast v-if="showTips" type="warn" :content="showTips" :close="() => (showTips = null)" />
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { http } from '@/utils/request'
import Toast from '@/components/dialog/Toast'
import browser from '@/utils/browser'
import Calendar from '@/components/calendar/mobile.vue'
import sync, {laserChangeMode, loadSourceScene, loadTargetScene , setPanoWithBim} from '@/utils/sync'

// 点位信息
let lastFakeApp = null
let panoData

// 是否BIM模式
const showBim = ref(browser.urlHasValue('bim'))
const showBimTips = ref(false)
const showTips = ref(null)
const bimChecked = ref(null)
const sourceFrame = ref(null)
const mode = ref(0)
const source = ref(null)
const target = ref(null)
const project = ref(null)


const scenes = computed(() => {
    if (!project.value) {
        return []
    }
    return project.value.sceneList.map(item => {
        return {
            num: item.num,
            type: item.type,
            createTime: item.createTime,
        }
    })
})
const sourceURL = computed(() => {
     
    /*if (source.value.type < 2) {
        let pose = ''
        // 获取当前点位旋转值
        if (sourceFrame.value && sourceFrame.value.contentWindow.app && sourceFrame.value.contentWindow.app.Camera) {
            let sdk = sourceFrame.value.contentWindow.app
            lastFakeApp = sync.views.createFakeApp(sourceFrame.value.contentWindow, true);
              
            //pose = '&'+sdk.Camera.getPoseUrlParams()
        }
        // 看看、看见场景
        return `smart-kankan.html?m=${source.value.num}`//`smart-kankan.html?m=${source.value.num}${pose}`
    } else {
        // 深时场景
        return `smart-kankan.html?m=${source.value.num}`//`smart-laser.html?m=${source.value.num}&dev`
    }*/ 
    
    if(lastFakeApp/*sourceFrame.value && (bimChecked.value || sourceFrame.value.contentWindow.app || sourceFrame.value.contentWindow.loaded)*/){
        sync.views.fakeAppUpdateInfo(sourceFrame.value.contentWindow)  //这两个怎么都会报错？ bim的得不到app.viewer
    }
    if(bimChecked.value){
        return `smart-bim.html?m=${project.value.bimData.bimOssFilePath}`
    }
    if(!source.value){
        return
    }
    if(source.value.type < 2) {
        return `smart-kankan.html?m=${source.value.num}`
    } else {
        return `smart-laser.html?m=${source.value.num}&dev`
    }
})

const onLoadSource = () => { 
    let win = sourceFrame.value.contentWindow 
        window.app = win
        
    let loaded = ()=>{
        if (lastFakeApp) {
            if(bimChecked.value || lastFakeApp.sceneType == 'bim'){//->bim
                sync.views.bindFakeWithBim(lastFakeApp, win, panoData) 
            }else{
                sync.views.bindWithSameFakeType(lastFakeApp,win) 
            }
            
              
        }
        if(project.value.sceneList.length) {
            lastFakeApp = sync.views.createFakeApp(sourceFrame.value.contentWindow);  
        }
    } 

 
     
    if(bimChecked.value){//bim
        win.sceneType = 'bim'
        win.loaded.then(sdk => { 
            loaded() 
        }) 
    }else if (source.value.type < 2) { 
        win.sceneType = 'kankan'
        let sdk = win.app 
        sdk.Scene.on('loaded', () => {
            loaded() 
        })  
    }else{ 
        win.sceneType = 'laser' 
        win.loaded.then(sdk => { 
            sync.views.laserInit(win, mode.value)
            loaded();
            
            /*setTimeout(()=>{//laser的代码中莫名会请求showPointCloud，所以尽量晚一点覆盖它
                if(win.Potree){
                    win.Potree.settings.displayMode = mode.value == 0 ? "showPanos" : "showPointCloud"
                }
            }, sync.views.settings.checkModeDelay)*/
            
         }) 
    }
     
     
}







const sourceDate = computed(() => {
    if (source.value) {
        return source.value.createTime.toDate()
    }
})

const sourceDays = computed(() => {
    const outDays = { year: [], month: [], day: [] }
    if (!scenes.value) {
        return outDays
    }
    const inDays = scenes.value.map(item => item.createTime.split(' ')[0].split('-'))

    inDays.forEach(item => {
        const [year, month, day] = item
        if (outDays.year.indexOf(year) == -1) {
            outDays.year.push(year)
        }
        if (outDays.month.indexOf(month) == -1) {
            outDays.month.push(month)
        }
        if (outDays.day.indexOf(day) == -1) {
            outDays.day.push(day)
        }
    })

    return outDays
})



const onModeChange = targetMode => {
    if (sourceFrame.value && sourceFrame.value.contentWindow.loaded) {
        sourceFrame.value.contentWindow.loaded.then(sdk => sdk.scene.changeMode(targetMode))
        mode.value = targetMode
        sync.views.laserChangeMode(mode.value)
    }
}

const onSelected = data => {
    if (!data.payload) {
        return
    }
    let { payload } = data
    let time = payload.format('YYYY-mm-dd')
    let find = scenes.value.find(c => c.createTime.indexOf(time) != -1)
    if (find) {
        if (find.num != source.value.num) {
            source.value = find
        }
    }
}

const onPrevDate = name => {
    let index = scenes.value.findIndex(item => item.num == source.value.num)
    if (index == -1) {
        return
    }
    if (--index == -1) {
        index = scenes.value.length - 1
    }
    source.value = scenes.value[index]
}
const onNextDate = name => {
    let index = scenes.value.findIndex(item => item.num == source.value.num)
    if (index == -1) {
        return
    }
    if (++index > scenes.value.length - 1) {
        index = 0
    }

    source.value = scenes.value[index]
}

// bim点击
const onBimChecked = () => {
    showBimTips.value = true

    setTimeout(() => {
        showBimTips.value = false
    }, 2000)

    if (!project.value || !project.value.bimData) {
        showTips.value = '未发现BIM文件'
        return
    }
    if (bimChecked.value) {
        bimChecked.value = false
        showBimTips.value = false
    } else {
        bimChecked.value = true
    }
}

onMounted(() => {
    const projectId = browser.valueFromUrl('projectId') || 1
    http.get(`smart-site/project/info?projectId=${projectId}`)
        .then(response => {
            if (response.success) {
                project.value = response.data
                if (showBim.value) {
                    onBimChecked()
                }
                if (project.value.sceneList.length) {
                    source.value = project.value.sceneList[0]
                }
                if(response.data.panos){
                    response.data.panos = JSON.parse(response.data.panos)
                    panoData = response.data.panos  //convert with bim
                }
                
            } else {
                showTips.value = response.message
            }
        })
        .catch(err => {
            showTips.value = '服务器连接失败'
        })
})
</script>

<style lang="scss" scoped>
main {
    width: 100%;
    height: 100%;
    iframe {
        width: 100%;
        height: 100%;
    }
    .tools {
        position: absolute;
        width: 100%;
        bottom: 40px;
        z-index: 2000;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        pointer-events: none;
        > div {
            pointer-events: all;
        }

        .item-mode {
            height: 50px;
            background: rgba(27, 27, 28, 0.8);
            box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
            border-radius: 47px 47px 47px 47px;
            border: 1px solid #000000;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 10px;
            margin-right: 10px;
            font-size: 16px;
            padding: 0 16px;
            div {
                cursor: pointer;
                font-size: 18px;
            }
            div:last-child {
                margin-left: 20px;
            }
            div.active {
                color: #0076f6;
            }
        }
    }

    .model {
        position: absolute;
        left: 15px;
        top: 20px;
        z-index: 1000;
        display: flex;
        flex-direction: column;
        span {
            position: absolute;
            left: 130%;
            top: 48%;
            background: rgba(27, 27, 28, 0.8);
            padding: 4px;
            border-radius: 4px;
            color: #fff;
            &::before {
                content: '';
                position: absolute;
                right: 100%;
                top: 50%;
                margin-top: -7px;
                width: 0;
                height: 0;
                border-top: 7px solid transparent;
                border-right: 14px solid rgba(27, 27, 28, 0.8);
                border-bottom: 7px solid transparent;
            }
        }
        > div {
            cursor: pointer;
            width: 50px;
            height: 50px;
            margin-top: 16px;
            background: rgba(27, 27, 28, 0.8);
            box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
            border-radius: 47px 47px 47px 47px;
            border: 1px solid #000000;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            > div {
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }
            &.active {
                color: #0076f6;
            }
            &.disable {
                opacity: 0.5;
            }
            i {
                font-size: 20px;
            }
        }
    }
}
</style>
<style lang="scss">
#app {
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
}
</style>
