<template>
    <AppHeader v-show="!fscChecked" :project="project" @getUserId="getUserId" :show-adjust="showAdjust" @update="onPointsUpdate" />
    <article>
        <main>
            <div class="split">
                <iframe ref="sourceFrame" v-if="sourceURL" :src="sourceURL" frameborder="0" @load="onLoadSource"></iframe>
                <div class="tools" v-if="source" v-show="showWidget && !showAdjust && !fscChecked && (dbsChecked || (!target && !bimChecked))">
                    <div class="item-date">
                        <calendar
                            name="source"
                            :count="scenes.length"
                            :controls="controls"
                            :value="sourceDate"
                            :highlighted="sourceDays"
                            @selected="onSelected"
                            @pick="onPickDate"
                            @prev="onPrevDate"
                            @next="onNextDate"
                        ></calendar>
                    </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" :class="{ active: showDensity }" @click="showDensity = !showDensity">
                        <span>{{ densityType.text }}</span>
                        <i class="iconfont icon-arrows_down"></i>
                        <ul>
                            <li v-for="density in densityTypes" @click="onDensityChange(density)">{{ density.text }}</li>
                        </ul>
                    </div>
                </div>
                <div class="points" v-if="showAdjust">
                    <div :class="{ active: points.p1 }" @click="onP1Click('left')">
                        <i class="iconfont" :class="[points.p1 ? 'icon-positioning01' : 'icon-positioning02']"></i>
                        <span>P1</span>
                    </div>
                    <div :class="{ active: points.p2 }" @click="onP2Click('left')">
                        <i class="iconfont" :class="[points.p2 ? 'icon-positioning01' : 'icon-positioning02']"></i>
                        <span>P2</span>
                    </div>
                </div>
            </div>
            <div class="split" v-if="target">
                <iframe ref="targetFrame" :src="targetURL" frameborder="0" @load="onLoadTarget"></iframe>
                <div class="tools" v-show="!fscChecked && !bimChecked">
                    <div class="item-date target">
                        <calendar
                            name="target"
                            :count="scenes.length"
                            :controls="controls"
                            :value="targetDate"
                            :highlighted="targetDays"
                            @selected="onSelected"
                            @pick="onPickDate"
                            @prev="onPrevDate"
                            @next="onNextDate"
                        ></calendar>
                    </div>
                </div>
                <div class="points" v-if="showAdjust">
                    <div :class="{ active: points.p1 }" @click="onP1Click('right')">
                        <i class="iconfont" :class="[points.p1 ? 'icon-positioning01' : 'icon-positioning02']"></i>
                        <span>P1</span>
                    </div>
                    <div :class="{ active: points.p2 }" @click="onP2Click('right')">
                        <i class="iconfont" :class="[points.p2 ? 'icon-positioning01' : 'icon-positioning02']"></i>
                        <span>P2</span>
                    </div>
                </div>
            </div>
            <div class="model" v-show="showWidget && !showAdjust">
                <div v-if="isLogin" class="file" :class="{ active: fileChecked, disable: fileDisable }" v-show="!fscChecked && !showBim">
                    <div @click="onFileChecked">
                        <i class="iconfont icon-note1"></i>
                        <span>{{ $t('home.tag') }}</span>
                    </div>
                </div>
                <div class="bim" :class="{ active: bimChecked, disable: bimDisable }" v-show="!fscChecked && !showBim">
                    <div @click="onBimChecked">
                        <i class="iconfont icon-BIM"></i>
                        <span>BIM</span>
                    </div>
                </div>
                <div class="dbs" :class="{ active: dbsChecked, disable: dbsDisable }" v-show="!fscChecked && !showBim">
                    <div @click="onDbsChecked">
                        <i class="iconfont icon-split_screen"></i>
                        <span>{{ $t('home.splitScreen') }}</span>
                    </div>
                </div>
                <div class="fsc" :class="{ active: fscChecked }" @click="onFscChecked">
                    <i class="iconfont" :class="[fscChecked ? 'icon-full_screen_selected' : 'icon-full_screen_normal']"></i>
                    <span>{{ $t('home.fullScreen') }}</span>
                </div>
            </div>
            <TagManager />
        </main>
    </article>
    <Toast v-if="showTips" type="warn" :content="showTips" :close="() => (showTips = null)" />
    <Files :show="fileChecked" @exit="() => (fileChecked = false)" />
</template>

<script setup>
import { ref, onMounted, computed, nextTick, provide, watch } from 'vue'
import { http } from '@/utils/request'

import browser from '@/utils/browser'
import Toast from '@/components/dialog/Toast'
import AppHeader from '@/components/header'
import Calendar from '@/components/calendar'
import Files from '@/components/files'
import TagManager from '@/components/files/TagManager'
import sync, { beforeChangeURL, loadSourceScene, loadTargetScene, setPanoWithBim, flyToP1P2 } from '@/utils/sync'
import i18n from '@/i18n'
const { t } = i18n.global
const isDev = process.env.VUE_APP_TEST == 1

const tags = ref([])
const notify = ref(null)
const isEdit = ref(false)
const isLogin = ref(false)
provide('tags', tags)
provide('notify', notify)
provide('isEdit', isEdit)
provide('isLogin', isLogin)
const userId = ref(localStorage.getItem('userId') || null)

const getUserId = id => {
    userId.value = id
}

// 是否BIM模式
const showBim = ref(browser.urlHasValue('bim'))
// 是否校准模式
const showSplit = ref(browser.urlHasValue('split'))
const showAdjust = ref(browser.urlHasValue('adjust'))

const bimChecked = ref()
const dbsChecked = ref(null)
const fscChecked = ref(null)
const fileChecked = ref(false)

const datepickName = ref(null)

const sourceFrame = ref(null)
const targetFrame = ref(null)

const mode = ref(0)

const source = ref(null)
const target = ref(null)
const project = ref(null)
const points = ref({ p1: null, p2: 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 showTips = ref(null)

const showDensity = ref(false)

const showWidget = computed(() => {
    if (fileChecked.value) {
        return false
    }
    return true
})

const scenes = computed(() => {
    if (!project.value) {
        return []
    }
    return project.value.sceneList.map(item => {
        return {
            num: item.num,
            type: item.type,
            createTime: item.createTime,
        }
    })
})
const controls = computed(() => {
    if (bimChecked.value) {
        return scenes.value.length > 1
    }
    return dbsChecked.value ? scenes.value.length > 2 : scenes.value.length > 1
})
const sourceURL = computed(() => {
    beforeChangeURL('source')

    if (bimChecked.value && !dbsChecked.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}${isDev ? '&dev' : ''}`
    } else {
        // 深时场景
        return `smart-laser.html?m=${source.value.num}${isDev ? '&dev' : ''}`
    }
})
const targetURL = computed(() => {
    if (bimChecked.value) {
        return `smart-bim.html?m=${project.value.bimData.bimOssFilePath}`
    }

    if (source.value.type < 2) {
        // 看看、看见场景
        return `smart-kankan.html?m=${target.value.num}${isDev ? '&dev' : ''}`
    } else {
        // 深时场景
        return `smart-laser.html?m=${target.value.num}${isDev ? '&dev' : ''}`
    }
})
const sourceDate = computed(() => {
    if (source.value) {
        return source.value.createTime.toDate()
    }
})

const targetDate = computed(() => {
    if (target.value) {
        return target.value.createTime.toDate()
    }
})

const sourceDays = computed(() => {
    let dates = []
    if (datepickName.value == 'source') {
        if (dbsChecked.value) {
            // 分屏模式
            if (bimChecked.value) {
                // BIM模式
                dates = scenes.value.map(item => item.createTime.toDate())
            } else {
                // 非BIM模式
                dates = scenes.value.filter(item => item.createTime != target.value.createTime).map(item => item.createTime.toDate())
            }
        } else {
            // 非分屏模式
            dates = scenes.value.map(item => item.createTime.toDate())
        }
    }
    return {
        dates: dates,
    }
})

const targetDays = computed(() => {
    let dates = []
    if (datepickName.value == 'target') {
        dates = scenes.value.filter(item => item.createTime != source.value.createTime).map(item => item.createTime.toDate())
    }
    return {
        dates: dates,
    }
})

const fileDisable = computed(() => {
    return false
})

const bimDisable = computed(() => {
    if (!project.value || !project.value.bimData) {
        return true
    }
})

const dbsDisable = computed(() => {
    if (scenes.value.length == 0) {
        // 没有场景的情况
        return 1
    }
    if (!bimChecked.value && scenes.value.length == 1) {
        // 只有1个场景的情况
        return 2
    }
})

const onLoadSource = () => {
    if (bimChecked.value && !dbsChecked.value) {
        // BIM单屏模式
        return
    }
    if (source.value.type < 2) {
        window['kankan'] = sourceFrame.value.contentWindow.app
        window['kankan'].TagManager.load(tags.value)
    } else {
        window['laser'] = sourceFrame.value.contentWindow.loaded
    }
    loadSourceScene(sourceFrame, source.value.type < 2 ? 'kankan' : 'laser', mode.value)
}
const onLoadTarget = () => {
    if (bimChecked.value) {
        loadTargetScene(targetFrame, 'bim')
    } else {
        loadTargetScene(targetFrame, target.value.type < 2 ? 'kankan' : 'laser', mode.value)
    }
}

const onModeChange = targetMode => {
    window.Log('changeMode:' + targetMode, '#3cffff')
    if (sync.sourceInst) {
        sync.sourceInst.loaded.then(sdk => sdk.scene.changeMode(targetMode))
        mode.value = targetMode
        sync.views.laserChangeMode(mode.value)
    }
}

const onDensityChange = density => {
    if (sync.sourceInst) {
        sync.sourceInst.loaded.then(sdk => {
            let data = sdk.scene.changePointDensity(density.type)
            sdk.scene.changeDensityPercent(data.percent)
        })
        densityType.value = density
    }
}

const onPickDate = name => {
    datepickName.value = name
}

const onSelected = data => {
    if (!data.payload) {
        return
    }
    let { name, payload } = data
    let date = payload.format('YYYY-mm-dd')
    let dates = (name == 'source' ? sourceDays : targetDays).value.dates.map(item => item.format('YYYY-mm-dd'))

    if (dates.indexOf(date) != -1) {
        let time = payload.format('YYYY-mm-dd HH:MM')
        let find = scenes.value.find(c => c.createTime.indexOf(time) != -1)
        if (find) {
            if (name == 'source') {
                if (find.num != source.value.num) {
                    source.value = find
                }
            } else {
                if (find.num != target.value.num) {
                    target.value = find
                }
            }
        }
    } else {
        showTips.value = t('home.dateScene')
    }

    datepickName.value = null
}

const onPrevDate = name => {
    let scene = null
    if (name == 'source') {
        scene = source
    } else {
        scene = target
    }
    let index = scenes.value.findIndex(item => item.num == scene.value.num)
    if (index == -1) {
        return
    }
    if (--index == -1) {
        index = scenes.value.length - 1
    }

    if (target.value && !bimChecked.value) {
        // 分屏模式判断
        if (name == 'source') {
            if (scenes.value[index].createTime == target.value.createTime) {
                index--
            }
        } else {
            if (scenes.value[index].createTime == source.value.createTime) {
                index--
            }
        }
        if (index == -1) {
            index = scenes.value.length - 1
        }
    }

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

    if (target.value && !bimChecked.value) {
        // 分屏模式判断
        if (name == 'source') {
            if (scenes.value[index].createTime == target.value.createTime) {
                index++
            }
        } else {
            if (scenes.value[index].createTime == source.value.createTime) {
                index++
            }
        }

        if (index > scenes.value.length - 1) {
            index = 0
        }
    }

    scene.value = scenes.value[index]
}

const onFileChecked = () => {
    fileChecked.value = !fileChecked.value
}

// bim点击
const onBimChecked = () => {
    if (bimDisable.value) {
        return (showTips.value = t('home.notFindFile'))
    }
    if (bimChecked.value) {
        bimChecked.value = false
        if (dbsChecked.value) {
            // 如果没有多场景数据，取消分屏
            if (scenes.value.length < 2) {
                onDbsChecked()
                return
            }

            // 判断是否分屏状态
            let index = scenes.value.findIndex(item => item.num == source.value.num)
            if (index == -1) {
                return
            }
            if (++index > scenes.value.length - 1) {
                index = 0
            }
            target.value = scenes.value[index]
        }
    } else {
        bimChecked.value = true
    }
}

// 分屏点击
const onDbsChecked = () => {
    if (dbsDisable.value && !dbsChecked.value) {
        return (showTips.value = t('home.notFindScene'))
    }
    dbsChecked.value = !dbsChecked.value
    if (dbsChecked.value) {
        if (bimChecked.value) {
            // BIM分屏
            source.value = scenes.value[scenes.value.length - 1]
            target.value = project.value.bimData
        } else {
            // 四维看看、激光场景分屏
            let index = scenes.value.findIndex(item => item.num == source.value.num)
            if (index == -1) {
                return
            }
            if (++index > scenes.value.length - 1) {
                index = 0
            }
            target.value = scenes.value[index]
        }
    } else {
        target.value = null
    }
}

// 全屏点击
const onFscChecked = () => {
    let element = document.documentElement

    fscChecked.value = !fscChecked.value

    if (fscChecked.value) {
        if (element.requestFullscreen) {
            element.requestFullscreen()
        } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen()
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen()
        } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen()
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen()
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen()
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen()
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen()
        }
    }
}

const onPointsUpdate = (type, data) => {
    points.value[type] = data
}

const onP1Click = type => {
    if (!points.value.p1) {
        showTips.value = t('home.notChoosePoint')
        return
    }
    console.log(points.value.p1)
    // todo 定位

    flyToP1P2(points.value.p1)
}

const onP2Click = type => {
    if (!points.value.p2) {
        showTips.value = t('home.notChoosePoint')
        return
    }
    // todo 定位

    flyToP1P2(points.value.p2)
}

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) {
                if (response.data) {
                    document.title = response.data.projectName
                    if (response.data.panos) {
                        try {
                            response.data.panos = JSON.parse(response.data.panos)
                            points.value.p1 = response.data.panos.p1
                            points.value.p2 = response.data.panos.p2
                            setPanoWithBim(response.data.panos)
                        } catch (error) {
                            console.error(error)
                        }
                    }
                    project.value = response.data
                    if (showBim.value) {
                        onBimChecked()
                    } else 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'))
                        }
                        if (showAdjust.value || showSplit.value) {
                            onBimChecked()
                            nextTick(() => onDbsChecked())
                        }
                    } else {
                        return (showTips.value = t('home.sceneDelete'))
                    }
                }
            } else {
                if (response.code == 4008) {
                    // 未登录
                    localStorage.removeItem('token')
                } else {
                    showTips.value = response.message
                }
            }
        })
        .catch(() => {
            showTips.value = t('code.failed')
        })

    http.post(`smart-site/marking/list`, {
        projectId: projectId,
        pageNum: 1,
        pageSize: 200,
    }).then(response => {
        if (response.data && response.data.list) {
            tags.value = response.data.list.map(item => {
                item.hotData.visible = false
                item.hotData.id = item.markingId
                item.hotData.createTime = item.createTime
                item.hotData.lastCreateBy = item.lastCreateBy
                return item.hotData
            })
        }
    })
})
</script>

<style lang="scss" scoped>
article {
    display: flex;
    width: 100%;
    height: 100%;
    overflow: hidden;
}
aside {
    width: 160px;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    h4 {
        font-size: 16px;
        text-align: center;
    }
    ul {
        margin-top: 20px;
    }
    li {
        margin: 0;
        padding: 0;
        font-size: 16px;
        margin-left: 20px;
        cursor: pointer;
        &:hover,
        &.active {
            color: #00c8af;
        }
    }
}
main {
    flex: 1;
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    &.full {
        .split {
            width: 50%;
        }
    }
    iframe {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1000;
        width: 100%;
        height: 100%;
        border: none;
        outline: none;
    }
    .split {
        margin-left: 2px;
        width: 100%;
        height: 100%;
        overflow: hidden;
        position: relative;
        &:first-child,
        &:last-child {
            margin-left: 0;
        }

        .points {
            position: absolute;
            left: 50%;
            top: 64px;
            z-index: 9999;
            display: flex;
            transform: translateX(-50%);

            div {
                cursor: pointer;
                margin-left: 20px;
                width: 70px;
                height: 88px;
                background: rgba(27, 27, 28, 0.8);
                box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25), inset 0px 0px 0px 2px rgba(255, 255, 255, 0.1);
                border-radius: 8px 8px 8px 8px;
                opacity: 1;
                border: 1px solid #000000;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                &.active {
                    color: #0076f6;
                }
                i {
                    font-size: 24px;
                }
                span {
                    font-size: 16px;
                    margin-top: 10px;
                }
            }
        }
    }
    .model {
        position: absolute;
        left: 50px;
        bottom: 40px;
        z-index: 1000;
        display: flex;
        flex-direction: column;
        > 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;
            }
            span {
                font-size: 12px;
                padding-top: 1px;
                transform: scale(0.8);
            }
        }
    }
    .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;
            }
        }
        .item-density {
            position: relative;
            cursor: pointer;
            height: 50px;
            width: 68px;
            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;
            &.active {
                ul {
                    display: block;
                }
                i {
                    transform: scale(0.8) rotate(180deg);
                }
            }
            span {
                margin-right: 4px;
            }
            i {
                transform: scale(0.8);
                font-size: 14px;
            }
            ul {
                display: none;
                position: absolute;
                left: 0;
                bottom: calc(100% + 10px);
                width: 68px;
                padding: 10px 0;
                border-radius: 12px;
                text-align: center;
                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;
                li {
                    padding: 5px 0;
                    &:hover {
                        color: #0076f6;
                    }
                }
            }
        }
    }
}
</style>
<style lang="scss">
#app {
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
}
.vuejs3-datepicker__calendar {
    background: rgba(27, 27, 28, 0.8);
    box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #000000;
    filter: blur(undefinedpx);
    color: #fff;
}
.vuejs3-datepicker__calendar-topbar {
    display: none !important;
}
.vuejs3-datepicker__calendar header .up:not(.disabled):hover {
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
}

.vuejs3-datepicker__calendar header .prev:after {
    border-left: 1px solid #fff;
    border-bottom: 1px solid #fff;
}
.vuejs3-datepicker__calendar header .prev:not(.disabled):hover {
    background: rgba(0, 0, 0, 0.3);
}

.vuejs3-datepicker__calendar header .next:after {
    border-top: 1px solid #fff;
    border-right: 1px solid #fff;
}
.vuejs3-datepicker__calendar header .next:not(.disabled):hover {
    background: rgba(0, 0, 0, 0.3);
}
.vuejs3-datepicker__calendar .cell {
    font-size: 16px !important;
    border-radius: 4px;
}
.highlighted {
    color: #076ede !important;
    background: transparent !important;
}
.selected {
    color: #fff !important;
    background: #0076f6 !important;
}
</style>
