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

                    <template v-if="isClient">
                        <el-form-item label="移动速度" prop="moveRate">
                            <el-radio-group v-model="form.moveRate" size="small">
                                <el-radio-button v-for="(it, idx) in speed" :label="it.label" :value="it.value"
                                    :key="idx" />
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="旋转速度" prop="turnRate">
                            <el-radio-group v-model="form.turnRate" size="small">
                                <el-radio-button v-for="(it, idx) in rotate" :label="it.label" :value="it.value"
                                    :key="idx" />
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="穿过障碍物" prop="canCrossWall">
                            <el-switch v-model="form.canCrossWall" :active-value="true" :inactive-value="false"
                                active-text="是" inactive-text="否" />
                        </el-form-item>
                        <el-form-item label="重力感应" prop="lookFactor">
                            <el-switch v-model="form.canGravity" :active-value="true" :inactive-value="false"
                                active-text="是" inactive-text="否" />
                        </el-form-item>
                    </template>
                    <template v-else>
                        <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="turnRate">
                            <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>
                    </template>
                    <el-form-item>
                        <el-button @click="startImmersionRoaming" ghost>开始漫游</el-button>
                        <el-button @click="endImmersionRoaming(99)" 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-row class="his-tool">
                    <el-col :span="12">
                        自动播放:
                        <el-checkbox v-model="autoPlay" />
                    </el-col>
                    <el-col :span="12">
                        <el-button type="primary" @click="playCancle">停止播放</el-button>
                    </el-col>
                </el-row>
                <el-table :data="historys" :empty-text="`暂无漫游历史`" :loading="loading" style="width: 100%" height="60vh">
                    <el-table-column prop="name" label="名称">
                        <template #default="scope">{{ scope.row.name }}[{{ scope.row.pointCount }}]</template>
                    </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 circle @click="playIR(scope.row)">
                                    <el-icon>
                                        <VideoPlay />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 1" content="暂停" placement="top">
                                <el-button circle @click="playIRPause(scope.row)">
                                    <el-icon>
                                        <VideoPause />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip v-else-if="scope.row.play === 2" content="继续" placement="top">
                                <el-button circle @click="playContinue(scope.row)">
                                    <el-icon>
                                        <VideoPlay />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="取消" placement="top">
                                <el-button circle @click="playCancle(scope.row)">
                                    <el-icon>
                                        <Close />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="重命名" placement="top">
                                <el-button circle @click="renamed(scope.row)">
                                    <el-icon>
                                        <Edit />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button circle @click="delCamera(scope.row, scope.$index)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-container">
                    <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 30, 50]" :total="pagination.total" layout="total, prev, pager, next"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="漫游重命名" v-model="visibleRenamed" width="280px" :before-close="() => visibleRenamed = false">
            <el-form ref="formRenamedRef" :rules="rulesRenamed" :model="formRenamed" label-width="80px">
                <el-form-item label="漫游名称" prop="name">
                    <el-input v-model="formRenamed.name" maxlength="20" placeholder="请输入名称"></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>
import { VideoPlay, VideoPause, Close, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, timeSelectProps } from 'element-plus'
import { roamingAdd, roamingGet, roamingUpdateByName, roamingDeleteById } from '@/api/bim/bim.js'
import useUserStore from '@/store/modules/user'

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

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

export default {
    name: 'PersonRoaming',
    components: {
        VideoPlay,
        VideoPause,
        Close,
        Edit,
        Delete,
    },
    props: {
        me: {
            type: Object,
            default: () => ({}),
        },
    },
    data() {
        return {
            isClient: false,
            data,
            data1,
            visibleRenamed: false,
            isRoaming: false,
            isRoamingHistory: false,
            tab: 'tab1',
            historys: [],
            loading: true,
            isMobile: false,
            autoPlay: true,
            isStop: 0,
            currentPrjId: null,
            currentComId: null,
            modelRenamed: null,
            form: {
                name: '',
                moveRate: 0.5,
                turnRate: 1,
                roamType: 'Third',
                canCrossWall: false,
                canGravity: true,
            },
            rulesRenamed: {
                name: [
                    {
                        required: true,
                        message: '请输入漫游名称',
                    },
                ],
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入漫游名称',
                    },
                ],
                moveRate: [
                    {
                        required: true,
                        message: '请输入移动速度系数',
                    },
                ],
                turnRate: [
                    {
                        required: true,
                        message: '请输入旋转速度系数',
                    },
                ],
            },
            formRenamed: {},

            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
            },
            rotate: [{ "label": "慢", "value": 1 }, { "label": "中", "value": 2 }, { "label": "快", "value": 3 }, { "label": "特快", "value": 4 }],
            speed: [{ "label": "慢", "value": 0.1 }, { "label": "中", "value": 0.2 }, { "label": "快", "value": 0.3 }, { "label": "特快", "value": 0.4 }]
        }
    },
    mounted() {
        window.xapp = this
        this.isClient = this.me.bimCfg?.clientApi == true
        if (this.isClient) {
            this.data = [{
                option: "↑ ← → ↓",
                title: "移动"
            },];
            this.data1 = [{
                option: "鼠标按左键前进后退",
                title: "视角前进后退"
            }, {
                option: "鼠标按左键左右移动",
                title: "视角左右环视"
            },];
            this.form.moveRate = this.speed[0].value
            this.form.turnRate = this.rotate[0].value
            this.form.canGravity = true
            this.form.canCrossWall = false
        }
        if (!this.isClient) {
            api.Plugin.addMiniMap()
            let options = {
                Anchor: 3,
                Offset: [70, -380],
                Size: 300,
            }
            api.Plugin.updateMiniMap(options)
        }
        const userStore = useUserStore()
        this.currentPrjId = userStore.currentPrjId
        this.currentComId = userStore.currentComId
    },
    methods: {
        ChangeTab(data) {
            if (data.paneName === 'tab2') {
                this.historys = []
                this.pagination.current = 1
                this.getRoamingList()
            }
        },
        getRoamingList() {
            this.loading = true
            roamingGet({
                roamingType: 1,
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                projectId: this.currentPrjId,
            }).then((res) => {
                this.loading = false
                this.pagination.total = res.data.pageInfo.totalCount

                if (res.data.rows.length > 0) {
                    res.data.rows.forEach((x) => (x.play = 0))
                }
                this.historys = res.data.rows
            })
        },
        GetObtainCoordinates({ clickStatus, callback }) {
            api.Public.pickupCoordinate(false)
            setTimeout(() => {
                api.Public.pickupCoordinate(true, function (data) {
                    api.Public.convertWorldToCartographicLocation(data, (position) => {
                        if (clickStatus && callback) {
                            callback(data)
                        }
                    })
                })
            })
        },
        startClientImmersionRoaming() {
            api.Camera.EndImmersionRoaming();
            api.Camera.PickIrBirthplace(A => {
                api.Camera.SetIRConfig({
                    bRecordLocus: true,
                    roamName: this.form.name,
                    canCrossWall: this.form.canCrossWall,
                    canGravity: this.form.canGravity,
                    moveRate: this.form.moveRate,
                    lookFactor: this.form.turnRate,
                    footerHeight: 1,
                    onIRStart: () => {
                        ElMessage.warning('请使用鼠标左键进行操作!')
                    },
                    onIREnd: (data) => {

                        this.doOnIREnd(data);
                    }

                });
                this.isRoaming = true
                api.Camera.StartImmersionRoaming()
            });
        },
        doOnIREnd(result) {
            ElMessage.success('漫游结束')
            if (this.stop === 0) {
                return
            }
            if (this.isClient) {
                result = this.$tryToJson(result.records, []);
            }
            let data = {
                vo: {
                    roamingType: 1,
                    speed: 0,
                    sort: 0,
                    time: 0,
                    projectId: this.currentPrjId,
                    comId: this.currentComId,
                    name: this.form.name,
                    modelId: api.m_model.keys().toArray().join(','),
                    roamingMode: this.isClient ? "Client1" : this.form.roamType,
                    moveRate: this.form.moveRate,
                    turnRate: this.form.turnRate,
                    points: JSON.stringify(result),
                    pointCount: result.length,
                },
            }
            roamingAdd(data).then((res) => {
                if (res.code == 0) {
                    ElMessage.success('保存成功！')
                    this.form.name = "";
                } else {
                    ElMessage.error('保存失败!')
                }
            })
        },
        startImmersionRoaming(e) {
            this.me && this.me.resetScene()
            e.preventDefault()
            if (!this.form.name) {
                ElMessage.warning('请输入漫游名称!')
                return
            }

            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    ElMessage.info('请点击选择漫游起始点')
                    if (this.isClient) {
                        this.startClientImmersionRoaming()
                        return;
                    }
                    this.GetObtainCoordinates({
                        clickStatus: true,
                        callback: (data) => {
                            this.GetObtainCoordinates({
                                clickStatus: false,
                            })
                            this.isStop = 0
                            api.Camera.setImmersiveRoamConfig({
                                roamingMode: this.form.roamType,
                                moveRate: this.form.moveRate,
                                turnRate: this.form.turnRate,
                                bRecordLocus: true,
                                onIREnd: (result) => {
                                    this.doOnIREnd(result)
                                },
                            })

                            this.isRoaming = true
                            api.Camera.startImmersiveRoam(data)
                        },
                    })
                }
            })
        },
        endImmersionRoaming(n) {
            if (this.isClient) {
                api.Camera.EndImmersionRoaming();
            }
            if (n) {
                this.isStop = 99
            } else {
                this.isStop = 0
            }
            if (this.isRoaming) {
                this.isRoaming = false
                this.me && this.me.resetScene()
            } else {
                ElMessage.warning('请先开启漫游')
            }
        },
        handleCancel() {
            this.endImmersionRoaming()
        },
        playIR(data) {
            this.playCancle()
            this.isRoamingHistory = true
            if (this.historys.findIndex((x) => x.play === 1) > -1) {
                this.historys.find((x) => x.play === 1).play = 0
            }
            data.play = 1
            let record = typeof data.points === 'string' ? JSON.parse(data.points) : data.points

            this.isStop = 0
            if (this.isClient) {
                this.isRoaming = true
                api.Camera.PlayIRCamera({
                    records: data.points,
                    complete: () => {
                        data.play = 0
                    }

                })
                return;
            }
            api.Camera.setImmersiveRoamConfig({
                roamingMode: data.roamingMode,
                moveRate: data.moveRate,
                turnRate: data.turnRate,
                bRecordLocus: false,
            })
            this.isRoaming = true
            setTimeout(() => {
                api.Camera.startImmersiveRoam([65.702301, 670.785328, 851.817162])
                setTimeout(() => {
                    api.Camera.playImmersiveRoam({
                        records: record,
                        isLoopPlay: this.autoPlay,
                        complete: function () {
                            data.play = 0
                        },
                    })
                }, 400)
            }, 100)
        },
        playIRPause(data) {
            data.play = 2
            if (this.isClient) {
                api.Camera.PlayIRPause();
            }else{
                api.Camera.pauseImmersiveRoam(false)
            }
        },
        playContinue(data) {
            data.play = 1
            if (this.isClient) {
                api.Camera.PlayIRContinue();
            } else {
                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 && data.play === 1) {
                data.play = 0
            } else {
                if (this.historys.findIndex((x) => x.play === 1) > -1) {
                    this.historys.find((x) => x.play === 1).play = 0
                }
            }
            if (this.isClient) {
                api.Camera.IRPlayCancle()
            } else {
                api.Camera.cancelPlayImmersiveRoam()
            }
            this.isRoamingHistory = false
            this.me && this.me.resetScene()
        },
        renamed(record) {
            this.visibleRenamed = true
            this.modelRenamed = record
            Object.assign(this.formRenamed, {
                name: record.name,
                remark: record.remark,
            })
        },
        handSaveRenamed() {
            this.$refs.formRenamedRef.validate((d) => {
                if (d) {
                    const data = {
                        id: this.modelRenamed.id,
                        name: this.formRenamed.name,
                    }
                    roamingUpdateByName(data).then((res) => {
                        if (res.code === 0) {
                            this.visibleRenamed = false
                            this.modelRenamed.name = this.formRenamed.name
                            ElMessage.success('保存成功')
                        } else {
                            ElMessage.error('保存失败')
                        }
                    })
                }
            })
        },
        delCamera(data, index) {
            this.$confirm(`确定要删除漫游 "${data.name}" 吗？`, '提示', {
                confirmButtonText: '确 认',
                cancelButtonText: '取 消',
                type: 'warning',
            }).then(() => {
                roamingDeleteById({ id: data.id }).then((res) => {
                    if (res.code === 0) {
                        this.historys.splice(index, 1)
                        ElMessage.success('删除成功！')
                    } else {
                        ElMessage.error('删除失败！')
                    }
                })
            })
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.getRoamingList()
        },
        handleCurrentChange(val) {
            this.pagination.current = val
            this.getRoamingList()
        },
    },
    beforeUnmount() {
        if (this.isRoaming) {
            if (this.isClient) {
                api.Camera.EndImmersionRoaming()
            } else {
                api.Camera.stopImmersiveRoam()
            }

        }
        if (this.isRoamingHistory) {
            if (this.isClient) {
                api.Camera.EndImmersionRoaming()
            } else {
                api.Camera.cancelPlayImmersiveRoam()
            }

        }
        if (!this.isClient) {
            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;
        }
    }

    .his-tool {
        font-size: 12px;
        margin-bottom: 8px;
    }

    .pagination-container {
        margin-top: 10px;
        height: 32px;
        display: flex;
        justify-content: flex-end;

        .el-pagination {
            font-size: 12px;

            .el-pagination__total,
            .el-pagination__sizes {
                margin-right: 16px;
            }
        }
    }

    .el-switch__label.is-active {
        color: #fff;
    }
}
</style>