<template>
    <div class="roaming-settings">
        <el-tabs v-model="tab" size="small" @tab-click="ChangeTab">
            <el-tab-pane label="漫游设置" name="1" 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="2" 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="操作">
                        <template #default="scope">
                            <el-tooltip v-if="scope.row.play === 0" content="播放" placement="top">
                                <el-button icon="el-icon-video-play" circle @click="playIR(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 1" content="暂停" placement="top">
                                <el-button icon="el-icon-video-pause" circle @click="playIRPause(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 2" content="继续" placement="top">
                                <el-button icon="el-icon-video-play" circle @click="playContinue(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="取消" placement="top">
                                <el-button icon="el-icon-video-close" circle @click="playCancle(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="重命名" placement="top">
                                <el-button icon="el-icon-edit" circle @click="renamed(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button icon="el-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>
const data = [
    {
        option: '鼠标左键',
        title: '前进、后退、旋转',
    },
    {
        option: '鼠标滚轮',
        title: '上扬、下俯',
    },
    {
        option: '按键(↑)或(↓)',
        title: '前后平移',
    },
    {
        option: '按键(←)或(→)',
        title: '左右旋转',
    },
]

const data1 = [
    {
        option: '按键(W)',
        title: '上浮',
    },
    {
        option: '按键(S)',
        title: '下沉',
    },
]
export default {
    data() {
        return {
            visibleRenamed: false,
            isRoaming: false,
            isRoamingHistory: false,
            tab: 1,
            data,
            data1,
            historys: [],
            form: {
                name: '',
                moveRate: 0.5, //移动速度系数
                turnRate: 1, //视角旋转速度(3°)
                roamType: 'Third',
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入漫游名称',
                    },
                ],
                moveRate: [
                    {
                        required: true,
                        message: '请输入移动速度系数',
                    },
                ],
                turnRate: [
                    {
                        required: true,
                        message: '请输入旋转速度系数',
                    },
                ],
            },
            formRenamed: {},
            visibleRenamed: false, //重命名显示
            modelRenamed: null,
            pagination: {
                current: 1,
                pageSize: 10,
            },
            loading: true,
            isMobile: false,
        }
    },
    mounted() {
        window.xapp = this
        //初始化漫游历史
        api.Plugin.addMiniMap()
        let options = {
            Anchor: 3,
            Offset: [70, -380],
            Size: 300,
            // Height: 1200
        }
        api.Plugin.updateMiniMap(options)
    },
    methods: {
        ChangeTab(data) {
            const that = this
            if (data == 2) {
                that.historys = []
                that.pagination.current = 1
                that.pagination.pageSize = Math.ceil(document.getElementsByClassName('roam-history')[0].offsetHeight / 40) + 1
                that.getRoamingList()
            }
        },
        async getRoamingList() {
            const that = this
            await getRoamingTrack({
                MaxResultCount: that.pagination.pageSize,
                SkipCount: (that.pagination.current - 1) * that.pagination.pageSize,
                ModelId: that.projectMessage.modelList[0].id,
            }).then((res) => {
                that.loading = false
                const pagination = {
                    ...that.pagination,
                }
                pagination.total = res.totalCount
                //
                if (res.items.length > 0) res.items.forEach((x) => (x.play = 0))
                that.historys = that.historys.concat(res.items)
                that.pagination = pagination
                if (res.totalCount > that.pagination.current * that.pagination.pageSize) {
                    that.updated()
                }
            })
        },
        updated() {
            const that = this
            that.$nextTick(() => {
                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 (that.pagination.total > that.pagination.current * that.pagination.pageSize) {
                            that.pagination.current++
                            that.getRoamingList()
                        }
                    }
                }
            })
        },
        startImmersionRoaming(e) {
            //开始漫游
            e.preventDefault()
            const that = this
            if (!that.form.name) {
                that.$message.warning('请输入漫游名称!')
                return
            }
            that.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    that.$message.info('请点击选择漫游起始点')
                    store.dispatch('GetObtainCoordinates', {
                        clickStatus: true,
                        callback: (data) => {
                            store.dispatch('GetObtainCoordinates', {
                                clickStatus: false,
                            })
                            //配置漫游
                            api.Camera.setImmersiveRoamConfig({
                                roamingMode: that.form.roamType,
                                moveRate: that.form.moveRate,
                                turnRate: that.form.turnRate,
                                bRecordLocus: true,
                                onIREnd: function (result) {
                                    that.$message.success('漫游结束')
                                    if (result) {
                                        setRoamingTrack({
                                            name: that.form.name,
                                            modelId: that.projectMessage.modelList[0].id,
                                            projectId: that.projectMessage.projectId,
                                            time: 0,
                                            remark: that.form.roamType,
                                            sort: 0,
                                            roamingPoints: result,
                                        }).then((res) => {
                                            res.record = result
                                            res.play = 0
                                            that.historys.push(res) //play 0未播放 1播放 2暂停
                                            that.form = {
                                                name: '',
                                                moveRate: 0.5,
                                                turnRate: 1,
                                                roamType: that.form.roamType,
                                            }
                                        })
                                    }
                                },
                            })
                            //启动漫游
                            that.isRoaming = true
                            api.Camera.startImmersiveRoam(data)
                        },
                    })
                }
            })
        },
        endImmersionRoaming() {
            if (this.isRoaming) {
                this.isRoaming = false
                api.Camera.stopImmersiveRoam()
                this.projectMessage.camera
                    ? api.Camera.setViewPort(this.projectMessage.camera)
                    : api.Model.location(this.projectMessage.modelId)
            } else {
                this.$message.warning('请先开启漫游')
            }
        },
        handleCancel() {
            this.endImmersionRoaming()
            this.$notification.destroy()
        },
        playIR(data) {
            //播放 play 0未播放 1播放 2暂停
            const that = this
            that.isRoamingHistory = true
            if (that.historys.findIndex((x) => x.play === 1) > -1) {
                //暂停正在播放的
                that.historys.find((x) => x.play === 1).play = 0
            }
            data.play = 1
            let record = typeof data.record == 'string' ? JSON.parse(data.record) : data.record
            api.Camera.setImmersiveRoamConfig({
                roamingMode: data.remark,
            })
            api.Camera.playImmersiveRoam({
                records: record, //轨迹数据>
                isLoopPlay: false,
                complete: function () {
                    data.play = 0
                },
            })
        },
        playIRPause(data) {
            //暂停播放
            data.play = 2
            api.Camera.pauseImmersiveRoam(false)
        },
        playContinue(data) {
            //继续播放
            data.play = 1
            api.Camera.pauseImmersiveRoam(true)
            if (this.historys.findIndex((x) => x.play === 1) > -1) {
                this.historys.find((x) => x.play === 1).play = 0
            }
        },
        playCancle(data) {
            //取消播放
            if (data.play === 1) {
                data.play = 0
            }
            api.Camera.cancelPlayImmersiveRoam() //取消播放
            this.isRoamingHistory = false
            this.projectMessage.camera
                ? api.Camera.setViewPort(this.projectMessage.camera)
                : api.Model.location(this.projectMessage.modelId)
        },
        //重命名
        renamed(record) {
            this.visibleRenamed = true
            this.modelRenamed = record
            this.$nextTick(() => {
                this.formRenamed.setFieldsValue({
                    name: record.name,
                    remark: record.remark,
                }) //,
            })
        },
        //重命名保存
        handSaveRenamed() {
            const that = this
            that.formRenamed.validateFields((err, values) => {
                if (!err) {
                    var data = Object.assign(that.modelRenamed, values)
                    updateRoamingTrack(data).then((res) => {
                        if (res) {
                            that.visibleRenamed = false
                            that.$message.success('保存成功')
                        } else {
                            that.$message.error('保存失败')
                        }
                    })
                }
            })
        },
        delCamera(data, index) {
            //删除漫游
            const that = this
            that.$confirm({
                cancelText: '取消',
                okText: '确定',
                title: `确定要删除漫游 “${data.name}” 吗？`,
                onOk() {
                    if (that.historys.find((x) => x.id === data.id).play != 0) {
                        api.Camera.cancelPlayImmersiveRoam()
                    }
                    that.historys.splice(index, 1)
                    deleteRoamingTrack(data.id).then((res) => {})
                    that.$message.success('删除成功！')
                },
            })
        },
        handleKeydown(event) {
            if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
                event.preventDefault()
                // 在这里添加你的上下键逻辑
            }
        },
    },
    destroyed() {
        const that = this
        if (that.isRoaming) {
            api.Camera.stopImmersiveRoam()
        }
        if (that.isRoamingHistory) {
            api.Camera.cancelPlayImmersiveRoam()
        }
        api.Plugin.deleteMiniMap()
        that.projectMessage.camera ? api.Camera.setViewPort(that.projectMessage.camera) : api.Model.location(that.projectMessage.modelId)
    },
    methods22: {
        doNav(n) {
            this.navIndex = n
        },
        endImmersionRoaming() {
            ;(this.romingVisible = !0), (this.roamName = '')
        },
        GetObtainCoordinates({ clickStatus, callback }) {
            api.Public.pickupCoordinate(false)
            setTimeout(() => {
                api.Public.pickupCoordinate(true, function (data) {
                    api.Public.convertWorldToCartographicLocation(data, (position) => {
                        if (clickStatus && callback) {
                            callback(data)
                        }
                    })
                })
            })
        },
        doRoaming() {
            debugger
            let e = this
            let that = this
            e.$message.warning('请点击模型选择漫游起点！')
            this.GetObtainCoordinates({
                clickStatus: true,
                callback: (data) => {
                    this.GetObtainCoordinates({
                        clickStatus: false,
                    })
                    //配置漫游
                    api.Camera.setImmersiveRoamConfig({
                        roamingMode: that.form.roamType,
                        moveRate: that.form.moveRate,
                        turnRate: that.form.turnRate,
                        bRecordLocus: true,
                        onIREnd: function (result) {
                            that.$message.success('漫游结束')
                            if (result) {
                                setRoamingTrack({
                                    name: that.name,
                                    modelId: that.projectMessage.modelList[0].id,
                                    projectId: that.projectMessage.projectId,
                                    time: 0,
                                    remark: that.form.roamType,
                                    sort: 0,
                                    roamingPoints: result,
                                }).then((res) => {
                                    res.record = result
                                    res.play = 0
                                    that.historys.push(res) //play 0未播放 1播放 2暂停
                                    that.form = {
                                        name: '',
                                        moveRate: 0.5,
                                        turnRate: 1,
                                        roamType: that.form.roamType,
                                    }
                                })
                            }
                        },
                    })
                },
            })
        },
    },
}
</script>
<style lang="scss">
.roaming-settings {
    padding: 0px 10px;
    .op-table {
        .cell {
            font-size: 12px;
        }
    }
}
</style>