<template>
    <div class="roaming-settings">
        <el-tabs v-model="tab" size="small" @tab-click="ChangeTab">
            <el-tab-pane label="漫游设置" name="tab1" class="scroll-box roam-history">
                <el-form ref="ruleForm" :model="form" :rules="rules" label-width="30%" @reset="handleCancel">
                    <el-form-item label="漫游名称" prop="name">
                        <el-input v-model="form.name" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item label="漫游类型" prop="roamType">
                        <el-select v-model="form.roamType" placeholder="请选择">
                            <el-option label="第一人称漫游" value="First"></el-option>
                            <el-option label="第三人称漫游" value="Third"></el-option>
                            <el-option label="飞行漫游" value="Flight"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="移动速度" prop="moveRate">
                        <el-input-number v-model="form.moveRate" :precision="2" :step="0.01" :min="0" placeholder="0.00" style="width: 100%"></el-input-number>
                    </el-form-item>
                    <el-form-item label="旋转速度" prop="lookFactor">
                        <el-input-number v-model="form.turnRate" :precision="2" :step="0.01" :min="0" placeholder="0.00" style="width: 100%"></el-input-number>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="startImmersionRoaming" ghost>开始漫游</el-button>
                        <el-button @click="endImmersionRoaming" ghost>结束漫游</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="data" border style="width: 100%" class="op-table">
                    <el-table-column prop="option" label="操作" width="180"></el-table-column>
                    <el-table-column prop="title" label="说明"></el-table-column>
                </el-table>
                <el-table :data="data1" border style="width: 100%" class="op-table" :show-header="false">
                    <el-table-column prop="option" label="操作" width="180"></el-table-column>
                    <el-table-column prop="title" label="说明"></el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="漫游历史" name="tab2" class="scroll-box roam-history roam-list-scroll">
                <el-table :data="historys" :empty-text="`暂无漫游历史`" :loading="loading" style="width: 100%">
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-tooltip v-if="scope.row.play === 0" content="播放" placement="top">
                                <el-button :icon="VideoPlay" circle @click="playIR(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 1" content="暂停" placement="top">
                                <el-button :icon="VideoPause" circle @click="playIRPause(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 2" content="继续" placement="top">
                                <el-button :icon="VideoPlay" circle @click="playContinue(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="取消" placement="top">
                                <el-button :icon="Close" circle @click="playCancle(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="重命名" placement="top">
                                <el-button :icon="Edit" circle @click="renamed(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button :icon="Delete" circle @click="delCamera(scope.row, scope.$index)"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="漫游重命名" :visible="visibleRenamed" width="280px" :before-close="() => visibleRenamed = false">
            <el-form :model="formRenamed" label-width="80px">
                <el-form-item label="漫游名称">
                    <el-input v-model="formRenamed.name"></el-input>
                </el-form-item>
                <el-form-item label="备注" v-show="false">
                    <el-input type="textarea" v-model="formRenamed.remark" :rows="4" placeholder="备注"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="visibleRenamed = false">取消</el-button>
                    <el-button type="primary" @click="handSaveRenamed">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { VideoPlay, VideoPause, Close, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roamingAdd, roamingGet } from '@/api/bim/bim.js'
import useUserStore from '@/store/modules/user'

const props = defineProps({
    me: {
        type: Object,
        default: () => ({}),
    },
})

const data = [
    {
        option: '鼠标左键',
        title: '前进、后退、旋转',
    },
    {
        option: '鼠标滚轮',
        title: '上扬、下俯',
    },
    {
        option: '按键(↑)或(↓)',
        title: '前后平移',
    },
    {
        option: '按键(←)或(→)',
        title: '左右旋转',
    },
]

const data1 = [
    {
        option: '按键(W)',
        title: '上浮',
    },
    {
        option: '按键(S)',
        title: '下沉',
    },
]

const visibleRenamed = ref(false)
const isRoaming = ref(false)
const isRoamingHistory = ref(false)
const tab = ref('tab1')
const historys = ref([])
const loading = ref(true)
const isMobile = ref(false)
const userStore = useUserStore()
const currentPrjId = ref(null)
const currentComId = ref(null)
const modelRenamed = ref(null)

const form = reactive({
    name: '',
    moveRate: 0.5,
    turnRate: 1,
    roamType: 'Third',
})

const rules = {
    name: [
        {
            required: true,
            message: '请输入漫游名称',
        },
    ],
    moveRate: [
        {
            required: true,
            message: '请输入移动速度系数',
        },
    ],
    turnRate: [
        {
            required: true,
            message: '请输入旋转速度系数',
        },
    ],
}

const formRenamed = reactive({})
const pagination = reactive({
    current: 1,
    pageSize: 10,
})

const ruleForm = ref(null)

onMounted(() => {
    window.xapp = this
    api.Plugin.addMiniMap()
    let options = {
        Anchor: 3,
        Offset: [70, -380],
        Size: 300,
    }
    api.Plugin.updateMiniMap(options)

    currentPrjId.value = userStore.currentPrjId
    currentComId.value = userStore.currentComId
})

const ChangeTab = (data) => {
    if (data.paneName === 'tab2') {
        historys.value = []
        pagination.current = 1
        pagination.pageSize = Math.ceil(document.getElementsByClassName('roam-history')[0].offsetHeight / 40) + 1
        getRoamingList()
    }
}

const getRoamingList = () => {
    loading.value = true
    roamingGet({
        pageSize: pagination.pageSize,
        pageNum: pagination.current,
        projectId: currentPrjId.value,
    }).then((res) => {
        loading.value = false
        pagination.total = res.data.pageInfo.totalCount

        if (res.data.rows.length > 0) {
            res.data.rows.forEach((x) => (x.play = 0))
        }
        historys.value = historys.value.concat(res.data.rows)

        if (res.data.pageInfo.totalCount > pagination.current * pagination.pageSize) {
            updated()
        }
    })
}

const updated = () => {
    const el = document.querySelector('.roam-list-scroll')
    const offsetHeight = el.offsetHeight
    el.onscroll = () => {
        const scrollTop = el.scrollTop
        const scrollHeight = el.scrollHeight
        if (offsetHeight + scrollTop - scrollHeight >= -1) {
            if (pagination.total > pagination.current * pagination.pageSize) {
                pagination.current++
                getRoamingList()
            }
        }
    }
}

const GetObtainCoordinates = ({ clickStatus, callback }) => {
    api.Public.pickupCoordinate(false)
    setTimeout(() => {
        api.Public.pickupCoordinate(true, function (data) {
            api.Public.convertWorldToCartographicLocation(data, (position) => {
                if (clickStatus && callback) {
                    callback(data)
                }
            })
        })
    })
}

const startImmersionRoaming = (e) => {
    e.preventDefault()
    if (!form.name) {
        ElMessage.warning('请输入漫游名称!')
        return
    }

    ruleForm.value.validate((valid) => {
        if (valid) {
            ElMessage.info('请点击选择漫游起始点')
            GetObtainCoordinates({
                clickStatus: true,
                callback: (data) => {
                    GetObtainCoordinates({
                        clickStatus: false,
                    })

                    api.Camera.setImmersiveRoamConfig({
                        roamingMode: form.roamType,
                        moveRate: form.moveRate,
                        turnRate: form.turnRate,
                        bRecordLocus: true,
                        onIREnd: (result) => {
                            ElMessage.success('漫游结束')
                            let data = {
                                vo: {
                                    projectId: currentPrjId.value,
                                    comId: currentComId.value,
                                    name: form.name,
                                    modelId: api.m_model.keys().toArray().join(','),
                                    roamingMode: form.roamType,
                                    moveRate: form.moveRate,
                                    turnRate: form.turnRate,
                                    points: JSON.stringify(result),
                                },
                            }
                            roamingAdd(data)
                        },
                    })

                    isRoaming.value = true
                    api.Camera.startImmersiveRoam(data)
                    console.log(data)
                },
            })
        }
    })
}

const endImmersionRoaming = () => {
    if (isRoaming.value) {
        isRoaming.value = false
        props.me.resetScene()
    } else {
        ElMessage.warning('请先开启漫游')
    }
}

const handleCancel = () => {
    endImmersionRoaming()
}

const playIR = (data) => {
    debugger
    isRoamingHistory.value = true
    if (historys.value.findIndex((x) => x.play === 1) > -1) {
        historys.value.find((x) => x.play === 1).play = 0
    }
    data.play = 1
    let record = typeof data.points === 'string' ? JSON.parse(data.points) : data.points
    api.Camera.setImmersiveRoamConfig({
        roamingMode: data.roamingMode,
        moveRate: form.moveRate,
        turnRate: form.turnRate,
        bRecordLocus: false,
    })
    api.Camera.playImmersiveRoam({
        records: record,
        isLoopPlay: true,
        complete: function () {
            data.play = 0
        },
    })
}

const playIRPause = (data) => {
    data.play = 2
    api.Camera.pauseImmersiveRoam(false)
}

const playContinue = (data) => {
    data.play = 1
    api.Camera.pauseImmersiveRoam(true)
    if (historys.value.findIndex((x) => x.play === 1) > -1) {
        historys.value.find((x) => x.play === 1).play = 0
    }
}

const playCancle = (data) => {
    if (data.play === 1) {
        data.play = 0
    }
    api.Camera.cancelPlayImmersiveRoam()
    isRoamingHistory.value = false
    props.me.resetScene()
}

const renamed = (record) => {
    visibleRenamed.value = true
    modelRenamed.value = record
    Object.assign(formRenamed, {
        name: record.name,
        remark: record.remark,
    })
}

const handSaveRenamed = () => {
    ruleForm.value.validateFields((err, values) => {
        if (!err) {
            const data = Object.assign(modelRenamed.value, values)
            updateRoamingTrack(data).then((res) => {
                if (res) {
                    visibleRenamed.value = false
                    ElMessage.success('保存成功')
                } else {
                    ElMessage.error('保存失败')
                }
            })
        }
    })
}

const delCamera = (data, index) => {
    ElMessageBox.confirm({
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        title: `确定要删除漫游 "${data.name}" 吗？`,
        onConfirm: () => {
            if (historys.value.find((x) => x.id === data.id).play !== 0) {
                api.Camera.cancelPlayImmersiveRoam()
            }
            historys.value.splice(index, 1)
            deleteRoamingTrack(data.id)
            ElMessage.success('删除成功！')
        },
    })
}

onBeforeUnmount(() => {
    if (isRoaming.value) {
        api.Camera.stopImmersiveRoam()
    }
    if (isRoamingHistory.value) {
        api.Camera.cancelPlayImmersiveRoam()
    }
    api.Plugin.deleteMiniMap()
    api.Model.location(api.m_model.keys().toArray()[0])
})
</script>
<style lang="scss">
.roaming-settings {
    width: 340px;
    padding: 0px 10px 10px;
    .op-table {
        .cell {
            font-size: 12px;
        }
    }
}
</style>