<template>
    <div class="system-busPresettingBit-add">
        <el-dialog v-model="isShowDialog" width="1250px" :close-on-click-modal="false" :destroy-on-close="true"
            @close="closeDialog">
            <template #header>
                <div
                    v-drag="['.system-busPresettingBit-add .el-dialog', '.system-busPresettingBit-add .el-dialog__header']">
                    {{ title }}:添加摄像头预置位
                </div>
            </template>
            <div class="info_list">
                <div class="video_box">
                    <div class="video-container" id="video-container" style="width: 870px; height: 600px"></div>
                </div>
                <div>
                    <el-button type="primary" style="margin: 0 20px 10px" @click="addPre">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加预置点
                    </el-button>
                    <el-table v-loading="loading" :data="tableData.data" border>
                        <el-table-column label="序号" align="center" type="index" width="55" />
                        <el-table-column label="名称" align="center" prop="presetName" width="120px"
                            show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.presetName" placeholder="请输入内容"
                                    @change="handleEdit(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="135px">
                            <template #default="scope">
                                <el-button type="primary" link @click="handleDebug(scope.row)">
                                    <el-icon>
                                        <View />
                                    </el-icon>调用
                                </el-button>
                                <el-button type="danger" link @click="handleDelete(scope.row)">
                                    <el-icon>
                                        <DeleteFilled />
                                    </el-icon>删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination style="padding: 5px 16px" v-show="tableData.total > 0" :total="tableData.total"
                        v-model:page="tableData.param.pageNum" v-model:limit="tableData.param.pageSize"
                        @pagination="busPresettingBitList" :layout="layout" />
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeUnmount, getCurrentInstance, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { listDevicePreset, addDevicePreset, updateDevicePreset, delDevicePreset, callDevicePreset } from '@/api/devicePreset';
import { getToken } from '@/api/securitySurveillance/index.js';

import EZUIKit from 'ezuikit-js';
import { ca } from 'element-plus/es/locale/index.mjs';
const emit = defineEmits(['update']);
const { proxy } = getCurrentInstance() as any;

const formRef = ref<HTMLElement | null>(null);
const menuRef = ref();
const loading = ref(false);

const isShowDialog = ref(false);
const layout = ref('total, prev, pager, next');
const title = ref('');
const updateRow = ref<any>(null);
const src = ref(null);
const flvPlayer = ref<any>(null);

const formData = ref({
    deviceSerial: undefined,
    channelNo: '1',
    presetName: undefined
});

const tableData = ref({
    data: [],
    total: 0,
    loading: false,
    param: {
        pageNum: 1,
        pageSize: 15,
        deviceSerial: ''
    }
});

// 打开弹窗
function openDialog(row: any) {
    resetForm();
    updateRow.value = row;
    title.value = row.deviceName;
    formData.value.deviceSerial = row.deviceSerial;
    tableData.value.param.deviceSerial = row.deviceSerial;
    isShowDialog.value = true;
    busPresettingBitList();
    nextTick(() => {
        videoPlay(row);
    });
}

// 添加预置点
function addPre() {
    ElMessageBox.prompt('请输入预置点名称', '添加预置点', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '请输入预置点名称'
    })
        .then(({ value }) => {
            formData.value.presetName = value;
            addDevicePreset(formData.value)
                .then(() => {
                    ElMessage.success('添加成功');
                    busPresettingBitList();
                })
                .finally(() => {
                    loading.value = false;
                });
        })
        .catch(() => { });
}

// 视频播放
function videoPlay(obj: any) {
    console.log('objobjobj', obj);

    getToken().then((res: any) => {
        if (res.msg == "ok" && obj.deviceSerial) {
            flvPlayer.value = new EZUIKit.EZUIKitPlayer({
                audio: '0',
                id: 'video-container',
                accessToken: res.data,
                url: `ezopen://open.ys7.com/${obj.deviceSerial}/1.hd.live`,
                template: 'pcLive',
                width: 870,
                height: 600,
                plugin: ['talk'],
                handleError: function (err: any) {
                    console.log(err);

                    if (err?.data?.ret === 20020) {
                        // 20020 是并发连接限制的错误码
                        ElMessage.error('当前观看人数已达上限，请稍后再试');
                    }
                }
            });
        }
    });
}

// 关闭弹窗
function closeDialog() {
    if (flvPlayer.value) {
        flvPlayer.value.destroy().then((data: any) => {
            console.log('promise 获取 数据', data);
        });
        flvPlayer.value = null;
    }
    isShowDialog.value = false;
}

// 获取列表
function busPresettingBitList() {
    loading.value = true;
    listDevicePreset(tableData.value.param).then((res: any) => {
        tableData.value.data = res.rows ?? [];
        tableData.value.total = res.total;
        loading.value = false;
    });
}

// 取消
function onCancel() {
    closeDialog();
}

// 删除
function handleDelete(row: any) {
    let msg = '你确定要删除所选数据？';
    let id: number[] = [];
    if (row) {
        msg = '此操作将永久删除数据，是否继续?';
        id = [row.id];
    }
    if (id.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return;
    }
    ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            const obj = {
                deviceSerial: row.deviceSerial,
                ids: id
            };
            delDevicePreset({
                id: row.id,
                deviceSerial: row.deviceSerial,
                channelNo: "1",
                presetIndex: row.presetIndex
            }).then((res: any) => {
                if (res.code === 200) {
                    ElMessage.success('删除成功');
                    busPresettingBitList();
                }
            });
        })
        .catch(() => { });
}

// 调用
function handleDebug(row: any) {
    callDevicePreset([{
        deviceSerial: row.deviceSerial,
        presetIndex: row.presetIndex,
        channelNo: "1",
        id: row.id
    }]).then((res: any) => {
        if (res.code === 200) {
            ElMessage.success('调用成功');
        }
    });
}

// 修改
function handleEdit(row: any) {
    const param = {
        id: row.id,
        deviceSerial: row.deviceSerial,
        presetName: row.presetName
    };
    updateDevicePreset(param)
        .then(() => {
            ElMessage.success('修改成功');
            busPresettingBitList();
        })
        .finally(() => {
            loading.value = false;
        });
}

// 重置表单
function resetForm() {
    formData.value = {
        deviceSerial: undefined,
        channelNo: '1',
        presetName: undefined
    };
}

onBeforeUnmount(() => {

    if (flvPlayer.value) {
        flvPlayer.value.destroy().then((data: any) => {
            console.log('promise 获取 数据', data);
        });
        flvPlayer.value = null;
    }
});

// ✅ 关键：暴露方法给父组件调用
defineExpose({
    openDialog,
    closeDialog
});
</script>

<style scoped lang="scss">
.system-busPresettingBit-add {
    .info_list {
        width: 100%;
        display: flex;
        height: 100%;

        .video_box {
            width: 75%;
            height: 600px;
            margin-right: 10px;

            .iframe {
                border: none;
                outline: none;
            }

            .video_air {
                width: 100%;
                height: 100%;
                object-fit: fill;
            }
        }
    }
}
</style>
