<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 class="item-density" v-if="source.type == 2 && mode == 1" @click="showDensity = true">
                <span>{{ densityType.text }}</span>
                <div @click.stop="showDensity = false" v-if="showDensity">
                    <ul>
                        <li class="title">{{ $t('home.thickness') }}</li>
                        <li v-for="density in densityTypes" @click="onDensityChange(density)">
                            {{ density.text }}<i class="iconfont" :class="{ 'icon-check': density.type == densityType.type }"></i>
                        </li>
                    </ul>
                </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, { loadSourceScene, loadTargetScene, setPanoWithBim } from '@/utils/sync'
import i18n from '@/i18n'
const { t } = i18n.global
const isDev = process.env.VUE_APP_TEST == 1
// 点位信息
let lastFakeApp = null
let panoData

// 是否BIM模式
const showBim = ref(browser.urlHasValue('bim'))
const showBimTips = ref(false)
const showTips = ref(null)
const showDensity = ref(false)
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 densityTypes = ref([
    { type: 'high', text: t('common.high') },
    { type: 'middle', text: t('common.middle') },
    { type: 'low', text: t('common.low') },
])

const densityType = ref(densityTypes.value[0])

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 (lastFakeApp && sourceFrame.value.contentWindow.fakeApp /* && sourceFrame.value && ( sourceFrame.value.contentWindow.app || sourceFrame.value.contentWindow.viewer)*/) {
        //fakeApp代表已经初始化完毕

        sync.views.fakeAppUpdateInfo(sourceFrame.value.contentWindow)
    }
    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}${isDev ? '&dev' : ''}`
    }
})

const onLoadSource = () => {
    let win = sourceFrame.value.contentWindow
    window.app = win

    let loaded = () => {
        if (lastFakeApp) {
            if (bimChecked.value || lastFakeApp.sceneType == 'bim') {
                //->bim   也可能是bim和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()
        })
    }
}

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 onDensityChange = density => {
    if (sourceFrame.value && sourceFrame.value.contentWindow.loaded) {
        sourceFrame.value &&
            sourceFrame.value.contentWindow.loaded.then(sdk => {
                let data = sdk.scene.changePointDensity(density.type)
                sdk.scene.changeDensityPercent(data.percent)
            })
        densityType.value = density
    }
    showDensity.value = false
}

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 = t('home.notFindFile')
        return
    }
    if (bimChecked.value) {
        bimChecked.value = false
        showBimTips.value = false
    } else {
        bimChecked.value = true
    }
}

onMounted(() => {
    const num = browser.valueFromUrl('m') || ''
    const projectId = browser.valueFromUrl('projectId') || 1
    http.get(`smart-site/project/info?projectId=${projectId}&sceneOrder=asc`)
        .then(response => {
            if (response.success) {
                project.value = response.data
                if (showBim.value) {
                    onBimChecked()
                }
                if (project.value.sceneList.length) {
                    if (num) {
                        source.value = project.value.sceneList.find(c => c.num == num)
                    } else {
                        source.value = project.value.sceneList[project.value.sceneList.length - 1]
                    }
                    if (!source.value) {
                        return (showTips.value = t('home.sceneDelete'))
                    }
                } else {
                    return (showTips.value = t('home.sceneDelete'))
                }
                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 = t('code.failed')
        })
})
</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;
            font-size: 16px;
            padding: 0 16px;
            div {
                cursor: pointer;
                font-size: 18px;
            }
            div:last-child {
                margin-left: 20px;
            }
            div.active {
                color: #0076f6;
            }
        }

        .item-density {
            position: relative;
            cursor: pointer;
            height: 50px;
            width: 50px;
            background: rgba(27, 27, 28, 0.8);
            box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
            border-radius: 50%;
            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 {
                position: fixed;
                left: 0;
                right: 0;
                bottom: 0;
                height: 100vh;
                z-index: 1000;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: flex-end;
                justify-content: center;
            }
            ul {
                width: 100%;
                padding-bottom: 20px;
                border-radius: 12px;
                background: rgba(27, 27, 28, 0.8);
                box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
                border: 1px solid #000000;
                list-style: none;
                .title {
                    justify-content: center;
                    font-weight: 500;
                    padding: 20px 0;
                    border-bottom: solid 1px rgba(255, 255, 255, 0.1);
                }
                li {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 25px 20px;
                    font-size: 18px;
                    i {
                        color: #0076f6;
                        font-size: 20px;
                    }
                }
            }
        }
    }

    .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>
