<template>
    <DashboardLayout ref="layout" layoutClass="special-situation-monitoring">
        <template #header-left>

        </template>
        <template #header-right>
            <!-- 日期 -->
            <DateTimeWidget />
        </template>

        <template #map>
            <!-- 路口列表 -->
            <div v-if="currentView === 'list-mode' && activeLeftTab === 'crossing'" class="list-mode-panel">
                <CrossingListPanel :onViewDetail="handleCrossingViewDetail"/>
            </div>
            <!-- 地图 -->
            <TongzhouTrafficMap v-else ref="trafficMapRef"
                :mode="activeLeftTab === 'crossing' ? '路口' : activeLeftTab === 'trunkLine' ? '干线' : activeLeftTab === 'specialDuty' ? '特勤' : ''"
                :search-offset-right="570"
                @map-crossing-click="handleMapCrossingClick"
                @map-crossing-mouseover="handleMapCrossingMouseover"
                @map-crossing-mouseout="handleMapCrossingMouseout"
                @bindTrunkMenuTree="handleTrunkMenuUpdate"
            />
        </template>


        <template #left>
            <div class="left-sidebar-wrap">
                <div class="left-sidebar-title">干线协调</div>
                <div class="left-sidebar-body">
                    <div v-if="trunkLineMenuData.length === 0" class="sidebar-loading">加载中...</div>
                    <template v-else>
                        <MenuItem v-for="item in trunkLineMenuData" :key="item.id" :node="item" :level="0"
                            @node-click="handleTrunkLineClick">
                        <template #label="{ node }">
                            <span v-if="node.children && node.children.length > 0">{{ node.label }}</span>
                            <span v-else>{{ node.label }} 绿波带</span>
                        </template>
                        </MenuItem>
                    </template>
                </div>
            </div>
        </template>

        <template #right>
            <!-- 模式切换按钮组 -->
            <div class="mode-switch" v-if="activeLeftTab === 'crossing'">
                <ButtonGroup v-model="currentView" :options="viewOptions" @select="onViewSelect" />
            </div>
        </template>

        <template #center>
            <!-- 顶部常驻图表区域（替代弹窗） -->
            <div class="top-charts-bar" v-if="currentView !== 'list-mode'">
                <!-- 总览Tab -->
                <template v-if="activeLeftTab === 'overview'">
                    <div class="top-chart-box overview-chart-box">
                        <OnlineStatusTabs :deviceData="onlineStatusData" />
                    </div>
                    <div class="top-chart-box overview-chart-box">
                        <DeviceStatusTabs :statusData="deviceFaultData" />
                    </div>
                </template>
                <!-- 路口Tab -->
                <template v-if="activeLeftTab === 'crossing'">
                    <div class="top-chart-box overview-chart-box">
                        <OnlineStatusTabs :deviceData="onlineStatusData" />
                    </div>
                    <div class="top-chart-box overview-chart-box">
                        <DeviceStatusTabs :statusData="deviceFaultData" />
                    </div>
                </template>
            </div>
        </template>

    </DashboardLayout>
</template>

<script>
import DashboardLayout from '@/layouts/DashboardLayout.vue';
import DateTimeWidget from '@/components/ui/DateTimeWidget.vue';
import TongzhouTrafficMap from '@/components/TongzhouTrafficMap.vue';
import MenuItem from '@/components/ui/MenuItem.vue';
import ButtonGroup from '@/components/ui/ButtonGroup.vue';
import CrossingListPanel from '@/components/ui/CrossingListPanel.vue';
import OnlineStatusTabs from '@/components/ui/OnlineStatusTabs.vue';
import DeviceStatusTabs from '@/components/ui/DeviceStatusTabs.vue';
import { apiGetTongzhouMenuTree, apiGetTasks, apiGetTrafficTimeSpace, apiGetCrossingTopCharts, apiGetSpecialTaskMonitorData, apiGetCrossingDetailData, apiGetDeviceStatus, apiGetDeviceFaultStatus } from '@/api';


export default {
    name: "TrunkCoordination",
    components: {
        DashboardLayout,
        DateTimeWidget,
        TongzhouTrafficMap,
        MenuItem,
        ButtonGroup,
        CrossingListPanel,
        OnlineStatusTabs,
        DeviceStatusTabs,
    },
    data() {
        return {
            // 左侧边栏数据
            activeLeftTab: 'trunkLine', // 默认选中干线Tab
            menuData: [],
            trunkLineMenuData: [],
            // 地图模式切换数据
            currentView: 'map-mode',
            viewOptions: [
                { label: '列表模式', value: 'list-mode' },
                { label: '地图模式', value: 'map-mode' },
            ],
            // 特勤表头
            tableColumns: [
                { label: '序号', key: 'id', width: '10%' },
                { label: '名称', key: 'name', width: '30%' },
                { label: '执行人', key: 'executor', width: '15%' },
                { label: '等级', key: 'level', width: '12%' },
                { label: '状态', key: 'status', width: '13%' },
                { label: '操作', key: 'action', width: '20%' }
            ],

            tableData: [],
            // 路口顶部图表数据
            crossingTopCharts: {},
            // 路口多选分屏
            crossingSelections: [],
            maxCrossingSlots: 4,
            // 在线状态 & 设备状态数据
            onlineStatusData: null,
            deviceFaultData: null,
        };
    },
    watch: {
        // 监听路由参数变化（解决多次从首页点击不同数据跳转过来，页面不刷新的问题）
        '$route.query': {
            handler() {
                this.checkRouteParams();
            },
            deep: true
        }
    },
    created() {

    },
    async mounted() {
        // 加载菜单和任务数据
        const [menuData, taskData, onlineData, faultData] = await Promise.all([
            apiGetTongzhouMenuTree(),
            apiGetTasks({ pageSize: 5 }),
            apiGetDeviceStatus(),
            apiGetDeviceFaultStatus(),
        ]);
        this.menuData = menuData || [];
        this.trunkLineMenuData = [];
        this.tableData = taskData?.list || taskData || [];
        this.onlineStatusData = onlineData || null;
        this.deviceFaultData = faultData || null;

        // 组件挂载时检查路由
        this.checkRouteParams();

    },
    methods: {
        // 处理地图鼠标滑入事件
        handleMapCrossingMouseover(mapData, lnglat, pixel) {
            console.log('父组件接收到了地图路口鼠标滑入事件:', mapData);
            // 组装模拟数据
            const scale = window.innerWidth / 1920;
            let nodeData = {
                id: mapData.id || (mapData.position[0] + mapData.position[1]),
                label: mapData.road,
                pixelX: pixel ? Math.round(pixel.x / scale) : 950,
                pixelY: pixel ? Math.round(pixel.y / scale) : 430,
            }
            // 离线/降级/故障：显示小弹窗提示状态
            const abnormalNames = ['离线', '降级', '故障'];
            if (abnormalNames.includes(mapData.statusLabel || mapData.name)) {
                const statusText = mapData.statusLabel || mapData.name;
                this.$refs.layout.openDialog({
                    id: 'offline_tip_' + nodeData.id,
                    title: nodeData.label,
                    component: 'OfflineTip',
                    width: 260,
                    height: 100,
                    center: false,
                    showClose: false,
                    noPadding: false,
                    draggable: false,
                    resizable: false,
                    position: { x: (nodeData.pixelX || 950) + 10, y: nodeData.pixelY || 430 },
                    data: { status: statusText, road: nodeData.label },
                });
                return;
            }
            console.log(nodeData);
            if (this.activeLeftTab === 'overview') { // 总览
                this.showOverviewDalogs(nodeData);
            } else if (this.activeLeftTab === 'crossing') { // 路口
                this.showOverviewDalogs(nodeData);
            }
        },
        // 处理地图鼠标滑出事件
        handleMapCrossingMouseout(mapData) {
            console.log('父组件接收到了地图路口鼠标滑出事件:', mapData);
            if (!mapData) return;
            const id = mapData.id || (mapData.position[0] + mapData.position[1]);
            this.$refs.layout.handleDialogClose('offline_tip_' + id);
            if (this.activeLeftTab === 'overview') { // 总览
                this.$refs.layout.handleDialogClose('crossing3_' + id);
            } else if (this.activeLeftTab === 'crossing') { // 路口
                this.$refs.layout.handleDialogClose('crossing3_' + id);
            }
        },
        // 处理地图点击事件
        handleMapCrossingClick(mapData, lnglat, pixel) {
            console.log('父组件接收到了地图路口点击事件:', mapData);
            // 离线/降级/故障状态不弹详情
            const abnormalNames = ['离线', '降级', '故障'];
            if (abnormalNames.includes(mapData.statusLabel || mapData.name)) {
                this.$msg({
                    title: '提示',
                    message: `路口「${mapData.road || mapData.id}」设备${mapData.statusLabel || mapData.name}，无法查看详情`,
                    duration: 3000,
                });
                return;
            }
            // 组装模拟数据
            const scale = window.innerWidth / 1920;
            let nodeData = {
                id: mapData.id || (mapData.position[0] + mapData.position[1]),
                label: mapData.road,
                // 反算为设计稿坐标（SmartDialog 内部会再乘 scale）
                pixelX: pixel ? Math.round(pixel.x / scale) : 950,
                pixelY: pixel ? Math.round(pixel.y / scale) : 430,
            }
            // 干线marker点击时，从菜单数据中匹配对应干线
            if (this.activeLeftTab === 'trunkLine' && mapData.id) {
                const matched = this.findTrunkMenuNode(mapData.id);
                if (matched) {
                    nodeData.id = matched.id;
                    nodeData.label = matched.label;
                    nodeData.intersections = matched.intersections;
                    nodeData.distances = matched.distances;
                }
            }
            console.log(nodeData);
            if (this.activeLeftTab === 'overview') { // 总览
                this.showCrossingDetailDialogs(nodeData);
            } else if (this.activeLeftTab === 'crossing') { // 路口
                this.showCrossingDalogs(nodeData);
            } else if (this.activeLeftTab === 'trunkLine') { // 干线
                this.showTrunkLineDalogs(nodeData);
            } else if (this.activeLeftTab === 'specialDuty') { // 特勤
                if (mapData.taskId) {
                    nodeData.id = mapData.taskId;
                }
                this.showSpecialDutyDalogs(nodeData);
            }
        },
        // 列表模式Tab切换
        onListTabSelect(tabName) {
            if (tabName !== 'crossing') {
                this.currentView = 'map-mode';
            }
            this.handleTabClick(tabName);
        },
        // 模式切换
        onViewSelect(item) {
            console.log('你点击了：', item.label);
            this.currentView = item.value;
            this.$refs.layout.clearDialogs(); // 清空全部弹窗
            this.crossingSelections = [];
            // 列表模式弹窗
            if (this.currentView === 'list-mode') {
                // this.$refs.layout.openDialog({
                //     id: 'crossing-list', // 这里的 ID 可以根据实际业务场景动态生成
                //     title: '',
                //     component: 'CrossingListPanel',
                //     width: 1920,
                //     height: 750,
                //     center: false,
                //     showClose: true,
                //     noPadding: false,
                //     enableDblclickExpand: false,
                //     position: { x: 100, y: 150 },
                //     data: {
                //         onViewDetail: (rowData) => this.handleCrossingViewDetail(rowData)
                //     }
                // });
            } else {
                this.loadCrossingTopCharts();
            }
        },
        // 处理tab点击
        handleTabClick(tabName) {
            console.log('父组件接收到了tab点击事件:', tabName);
            this.$refs.layout.clearDialogs(); // 清空全部弹窗
            this.crossingSelections = [];
            this.showTopChartDalogs(); // 根据当前Tab显示对应的顶部常驻图表
        },
        // 处理菜单folder标题点击：计算子区路口中心坐标，移动地图
        handleFolderClick(nodeData) {
            console.log('父组件接收到了文件夹点击事件:', nodeData);
            const leaves = [];
            const collect = (nodes) => {
                if (!Array.isArray(nodes)) return;
                for (const n of nodes) {
                    if (n.children) collect(n.children);
                    else if (n.lng && n.lat) leaves.push(n);
                }
            };
            collect(nodeData.children || []);
            if (leaves.length === 0 || !this.$refs.trafficMapRef) return;

            const avgLng = leaves.reduce((s, n) => s + n.lng, 0) / leaves.length;
            const avgLat = leaves.reduce((s, n) => s + n.lat, 0) / leaves.length;
            const zoom = leaves.length <= 6 ? 15 : 14;
            const map = this.$refs.trafficMapRef.map;
            if (map) map.setZoomAndCenter(zoom, [avgLng, avgLat], false, 500);
        },
        // 处理菜单点击
        handleMenuClick(nodeData) {
            console.log('父组件接收到了最底层路口点击事件:', nodeData);
            // 通过地图组件获取像素坐标（如果有经纬度的话）
            // if (nodeData.lng && nodeData.lat && this.$refs.trafficMapRef) {
            //     // 地图联动
            //     this.$refs.trafficMapRef.focusByLocation([nodeData.lng, nodeData.lat]);

            //     const pixel = this.$refs.trafficMapRef.lngLatToPixel(nodeData.lng, nodeData.lat);
            //     if (pixel) {
            //         const scale = window.innerWidth / 1920;
            //         nodeData.pixelX = Math.round(pixel.x / scale) + 20;
            //         nodeData.pixelY = Math.round(pixel.y / scale);
            //     }
            // }

            // 根据Tab来显示不同的弹窗内容
            if (this.activeLeftTab === 'overview') { // 总览
                // 临时逻辑，有真实接口后可以删除
                const index = Math.floor(Math.random() * 10);
                const position = localStorage.getItem(`pos${index + 1}`).split(',');

                // 地图联动
                this.$refs.trafficMapRef.focusByLocation([Number(position[0]), Number(position[1])]);
                
                this.showOverviewDalogs(nodeData);
            } else if (this.activeLeftTab === 'crossing') { // 路口
                this.showCrossingDalogs(nodeData);
            } else if (this.activeLeftTab === 'trunkLine') { // 干线
                this.showTrunkLineDalogs(nodeData);
            } else if (this.activeLeftTab === 'specialDuty') { // 特勤
                this.showSpecialDutyDalogs(nodeData);
            }
        },
        // 处理弹窗双击展开（通过 onExpand 回调从 Layout 传入）
        handleDoubleClickExpend(nodeData) {
            console.log('处理弹窗双击事件', nodeData);
            if (this.activeLeftTab === 'crossing' || this.activeLeftTab === 'overview') {
                this.showCrossingDetailDialogs(nodeData);
            }
        },
        // 显示顶部常驻图表（根据当前Tab状态）
        showTopChartDalogs() {
            if (this.activeLeftTab === 'crossing') {
                this.loadCrossingTopCharts();
            }
        },
        // 显示总览弹窗组
        showOverviewDalogs(nodeData) {
            console.log('显示总览弹窗组', nodeData.id, nodeData.label);
            // 路口弹窗
            this.$refs.layout.openDialog({
                id: 'crossing3_' + nodeData.id, // 这里的 ID 可以根据实际业务场景动态生成
                title: nodeData.label,
                component: 'CrossingPanel',
                width: 260,
                height: 260,
                center: false,
                showClose: true,
                position: { x: (nodeData.pixelX || 950) + 20, y: nodeData.pixelY || 430 },
                noPadding: false,
                data: {
                    ...nodeData,
                    onExpand: (data) => this.handleDoubleClickExpend(data)
                },
                onClose: () => {
                    // this.$refs.layout.handleDialogClose('top-chart-crossing-1');
                    // this.$refs.layout.handleDialogClose('top-chart-crossing-2');
                }
            });
        },
        async loadCrossingTopCharts() {
            try {
                this.crossingTopCharts = await apiGetCrossingTopCharts();
            } catch (e) { /* ignore */ }
        },
        // 显示路口弹窗组（多选分屏）
        async showCrossingDalogs(nodeData) {
            console.log('路口多选', nodeData.id, nodeData.label);

            // 0. 离线检查
            const detailData = await apiGetCrossingDetailData(nodeData.id, { iconMode: 'simple' });
            if (detailData?.intersectionData?.status !== '在线') {
                this.$msg({
                    title: '提示',
                    message: `路口「${nodeData.label || nodeData.id}」设备离线，无法查看详情`,
                    duration: 3000,
                });
                return;
            }

            // 1. 已选中 → 不重复操作
            const existIndex = this.crossingSelections.findIndex(c => c.id === nodeData.id);
            if (existIndex !== -1) {
                return;
            }

            // 2. 已满 → 先进先出
            if (this.crossingSelections.length >= this.maxCrossingSlots) {
                this.crossingSelections.shift();
            }

            // 3. 追加选中，带上预加载数据避免重复请求
            this.crossingSelections.push({ ...nodeData, _preloadedData: detailData });

            // 4. 打开或更新弹窗
            this.openCrossingMultiView();
        },

        openCrossingMultiView() {
            this.$refs.layout.openDialog({
                id: 'crossing-multi-view',
                title: '',
                component: 'CrossingMultiView',
                width: 1400,
                height: 700,
                center: false,
                position: { x: 500, y: 150 },
                showClose: false,
                noPadding: true,
                enableDblclickExpand: false,
                draggable: false,
                data: {
                    crossings: [...this.crossingSelections],
                    maxSlots: this.maxCrossingSlots,
                    onRemove: (id) => this.handleCrossingRemove(id),
                    onReorder: (newOrder) => {
                        this.crossingSelections = newOrder;
                    }
                },
                onClose: () => {
                    this.crossingSelections = [];
                }
            });
        },

        handleCrossingRemove(id) {
            this.crossingSelections = this.crossingSelections.filter(c => c.id !== id);
            if (this.crossingSelections.length === 0) {
                this.$refs.layout.handleDialogClose('crossing-multi-view');
            } else {
                this.openCrossingMultiView();
            }
        },

        // 单个路口详情弹窗（总览双击展开等场景使用）
        async showCrossingDetailDialogs(nodeData) {
            console.log('显示路口详情弹窗组', nodeData.id, nodeData.label);
            const detailData = await apiGetCrossingDetailData(nodeData.id, { iconMode: 'simple' });
            if (detailData?.intersectionData?.status !== '在线') {
                this.$msg({
                    title: '提示',
                    message: `路口「${nodeData.label || nodeData.id}」设备离线，无法查看详情`,
                    duration: 3000,
                });
                return;
            }
            const dialogId = 'crossing_detail' + nodeData.id;
            this.$refs.layout.openDialog({
                id: dialogId,
                title: ' ',
                component: 'CrossingDetailPanel',
                width: 1315,
                height: 682,
                center: false,
                showClose: true,
                position: { x: 500, y: 170 },
                noPadding: false,
                enableDblclickExpand: false,
                data: { ...nodeData, preloadedData: detailData },
                headerComponent: 'CrossingDetailHeader',
                headerProps: {
                    currentRoute: { ...(detailData?.currentRoute || {}), name: nodeData.label || detailData?.currentRoute?.name },
                    intersectionData: detailData?.intersectionData || {},
                    cycleLength: detailData?.cycleLength || 0,
                }
            });
        },
        // 路口列表模式下弹窗
        handleCrossingViewDetail(rowData) {
            console.log('显示路口列表查看', rowData);
            this.showCrossingDetailDialogs(rowData);
        },
        // 显示干线弹窗组
        // 干线菜单叶子节点点击
        handleTrunkLineClick(nodeData) {
            console.log('干线菜单点击:', nodeData);
            this.showTrunkLineDalogs(nodeData);
        },
        findTrunkMenuNode(markerId) {
            // 从 marker ID（如 trunk_1_point_3）提取干线编号（trunk_1）
            const trunkId = String(markerId).replace(/_point_\d+$/, '');
            const leaves = [];
            const walk = (nodes) => {
                if (!Array.isArray(nodes)) return;
                for (const n of nodes) {
                    if (n.children && n.children.length > 0) walk(n.children);
                    else leaves.push(n);
                }
            };
            walk(this.trunkLineMenuData);
            return leaves.find(n => n.id === trunkId) || null;
        },
        handleTrunkMenuUpdate(segments) {
            this.trunkLineMenuData = [{
                id: 'trunk_root',
                label: '主控中心',
                icon: 'icon-control',
                isOpen: true,
                children: [{
                    id: 'trunk_beijing',
                    label: '北京市交警总队',
                    icon: 'icon-police',
                    isOpen: true,
                    children: [{
                        id: 'trunk_tongzhou',
                        label: '通州区',
                        icon: 'icon-district',
                        isOpen: true,
                        children: (() => {
                            const list = segments.slice(0, 6);
                            if (list[5]) list[5] = { ...list[5], label: '张台路与湖亦路路口' };
                            return list;
                        })()
                    }]
                }]
            }];
        },
        async showTrunkLineDalogs(nodeData) {
            console.log('显示干线弹窗组', nodeData.id, nodeData.label);
            // 优先使用菜单节点自带的路口和距离数据
            let tsData;
            if (nodeData.intersections && nodeData.distances) {
                tsData = await apiGetTrafficTimeSpace({
                    label: nodeData.label,
                    intersections: nodeData.intersections,
                    distances: nodeData.distances,
                });
            } else {
                tsData = await apiGetTrafficTimeSpace({ label: nodeData.label });
            }
            this.$refs.layout.openDialog({
                id: nodeData.id,
                title: nodeData.label + ' 绿波带',
                component: 'TrafficTimeSpace',
                width: 1200,
                height: 700,
                center: false,
                position: { x: 500, y: 150 },
                showClose: true,
                noPadding: false,
                data: tsData,
            });
        },
        // 显示特勤弹窗组
        showSpecialDutyDalogs(nodeData) {
            console.log('显示特勤弹窗组', nodeData.id, nodeData.label);
            this.openDutyDetailDialog(nodeData);
        },
        // === 解析路由参数并执行对应操作 ===
        checkRouteParams() {
            // 统一参数接收：特勤接收 id，路口接收 intersectionName 和 plan
            const { tab, action, id, } = this.$route.query;

            if (!tab) return; // 如果没有传递 tab 参数，说明是正常访问，不处理

            // 1. 处理“特勤线路”跳转
            if (tab === 'specialDuty') {
                this.activeLeftTab = 'specialDuty'; // 切换到左侧【特勤】Tab
                this.handleTabClick('specialDuty'); // 手动触发 Tab 切换事件，更新顶部图表

                // 这里判断的条件改为 id
                if (action === 'open-dialog' && id) {
                    this.$nextTick(() => {
                        this.openDutyDetailDialog({id: id, label: '特勤路口'}); // 打开特勤弹窗
                    });
                }
            }

            // 2. 处理“关键路口”跳转
            else if (tab === 'crossing') {
                this.activeLeftTab = 'crossing'; // 切换到左侧【路口】Tab
                this.handleTabClick('crossing'); // 手动触发 Tab 切换事件，更新顶部图表

                if (action === 'open-dialog') {
                    this.$nextTick(() => {
                        // 构造一个假的 nodeData 传给详情弹窗方法
                        this.showCrossingDetailDialogs({
                            id: 'route_' + new Date().getTime(), // 动态生成一个ID防重复
                            label: '路口详情',
                        });
                    });
                }
            }
        },

        // === 特勤详情弹窗 (你需要根据实际组件名替换) ===
        async openDutyDetailDialog(nodeData) {
            console.log('准备打开特勤线路详情：', nodeData);
            // 1. 获取数据
            const panelData = await apiGetSpecialTaskMonitorData(nodeData.id);

            const id = 'special-task-dialog' + new Date().getTime();
            // 2. 呼出弹窗
            this.$refs.layout.openDialog({
                id: id,
                title: ' ', // 留空以隐藏默认标题，使用自定义 Header
                width: 1400, // 弹窗宽一点，容纳 3 列
                height: 700,
                center: false,
                showClose: true,
                noPadding: true, // 去除默认内边距，让内部组件自己控制
                position: {x: 200, y: 150},
                // 挂载主体组件和数据
                component: 'SpecialTaskMonitorPanel',
                data: { panelData: panelData },
                // 挂载自定义 Header 和数据
                headerComponent: 'TaskMonitorHeader',
                headerProps: {
                    taskData: panelData.taskInfo,
                    onStartTask: () => {
                        console.log('点击了立即执行');
                        panelData.taskInfo.status = '进行中';
                        const tableRow = this.tableData.find(r => r.id === nodeData.id);
                        if (tableRow) tableRow.status = '进行中';
                    },
                    onEndTask: () => {
                        console.log('点击了立即结束');
                        panelData.taskInfo.status = '已完成';
                        const tableRow = this.tableData.find(r => r.id === nodeData.id);
                        if (tableRow) tableRow.status = '已完成';
                    }
                }
            });
            return panelData;
        },
        handleSpecialTaskView(row) {
            console.log('查看特勤线路，当前数据：', row);
            this.openDutyDetailDialog(row);
        },
        async handleSpecialTaskStart(row) {
            console.log('立即执行特勤任务：', row);
            const panelData = await this.openDutyDetailDialog(row);
            this.$msg({
                title: '操作确认',
                message: `确认立即执行任务「${row.name}」？`,
                duration: 0,
                showConfirm: true,
                showCancel: true,
                confirmText: '确认执行',
                noBackdrop: true,
                onConfirm: () => { row.status = '进行中'; panelData.taskInfo.status = '进行中'; }
            });
        },
        async handleSpecialTaskEnd(row) {
            console.log('立即结束特勤任务：', row);
            const panelData = await this.openDutyDetailDialog(row);
            this.$msg({
                title: '操作确认',
                message: `确认立即结束任务「${row.name}」？`,
                duration: 0,
                showConfirm: true,
                showCancel: true,
                confirmText: '确认结束',
                noBackdrop: true,
                onConfirm: () => { row.status = '已完成'; panelData.taskInfo.status = '已完成'; }
            });
        },
        async handleSpecialTaskRestart(row) {
            console.log('重新开始特勤任务：', row);
            const panelData = await this.openDutyDetailDialog(row);
            this.$msg({
                title: '操作确认',
                message: `确认重新开始任务「${row.name}」？`,
                duration: 0,
                showConfirm: true,
                showCancel: true,
                confirmText: '确认开始',
                noBackdrop: true,
                onConfirm: () => { row.status = '进行中'; panelData.taskInfo.status = '进行中'; }
            });
        },


    }
}
</script>
<style scoped>
.mode-switch {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
}

.mode-switch>div {
    width: 200px;
}
.left-sidebar-wrap {
    display: flex;
    flex-direction: column;
    max-width: 400px;
}
.left-sidebar-title {
    font-size: clamp(14px, 1.04vw, 20px);
    font-weight: bold;
    color: #e0e8f0;
    padding: 12px 0;
    letter-spacing: 2px;
}
.left-sidebar-body {
    background: rgba(17, 36, 70, 0.9);
    outline: 2px solid #3760A9;
    outline-offset: -2px;
    height: 700px;
    overflow: auto;
}
.sidebar-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 120px;
    color: #758599;
    font-size: 14px;
}
.duty-table {
    margin-top: 10px;
}
.action-btn {
    cursor: pointer;
    color: #4da8ff;
    margin-right: 10px;
}
.action-btn:hover {
    text-decoration: underline;
}
.action-start {
    color: #67c23a;
}
.action-end {
    color: #f56c6c;
}
.top-charts-bar {
    display: flex;
    justify-content: center;
    gap: clamp(10px, 1.04vw, 20px);
    pointer-events: none;
}
.top-chart-box {
    pointer-events: auto;
    flex-shrink: 0;
    background: radial-gradient(circle at 20% 0%, rgba(40,120,200,0.5) 0%, rgba(20,60,130,0.7) 70%);
    box-shadow: inset 0px 0px 0.625rem 0px rgba(88, 146, 255, 0.4), inset 1.25rem 0px 1.875rem -0.625rem rgba(88, 146, 255, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: clamp(6px, 0.625vw, 12px);
    overflow: hidden;
}
/* --- 总览Tab图表尺寸适配 (原 300x160) --- */
.overview-chart-box {
    /* clamp(最小值, 理想值(1920下比例), 最大值) */
    width: clamp(200px, 15.625vw, 300px);
    height: clamp(106px, 8.333vw, 160px);
}

/* --- 路口Tab图表尺寸适配 (原 228x124) --- */
.crossing-chart-box {
    width: clamp(152px, 11.875vw, 228px);
    height: clamp(82px, 6.458vw, 124px);
}
::v-deep .list-mode-panel {
    position: absolute;
    inset: 0;
    padding: 150px 30px 30px 30px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.list-mode-tabs {
    flex-shrink: 0;
    max-width: 400px;
}
.duty-name {
    display: inline-block;
    max-width: 8em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
}
/* 针对特勤 Tab 单独剥离背景和边框 */
::v-deep .special-duty-pane {
    padding: 10px 20px;
}

</style>
