<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
                amapKey="db2da7e3e248c3b2077d53fc809be63f"
                securityJsCode="a7413c674852c5eaf01d90813c5b7ef6"
                :mode="activeLeftTab === 'crossing' ? '路口' : activeLeftTab === 'trunkLine' ? '干线' : activeLeftTab === 'specialDuty' ? '特勤' : ''"
                @map-crossing-click="handleMapCrossingClick"
            />
        </template>


        <template #left>
            <!-- 左侧Tab菜单栏 -->
            <div class="left-sidebar-wrap" v-if="currentView !== 'list-mode'">
                <TechTabs v-model="activeLeftTab" type="underline" @tab-click="handleTabClick">
                    <TechTabPane label="总览" name="overview" class="menu-scroll-view">
                        <MenuItem theme="tech" v-for="item in menuData" :key="item.id" :node="item" :level="0"
                            @node-click="handleMenuClick" />
                    </TechTabPane>
                    <TechTabPane label="路口" name="crossing" class="menu-scroll-view">
                        <MenuItem theme="tech" v-for="item in menuData" :key="item.id" :node="item" :level="0"
                            @node-click="handleMenuClick" />
                    </TechTabPane>
                    <TechTabPane label="干线" name="trunkLine" class="menu-scroll-view">
                        <MenuItem v-for="item in menuData" :key="item.id" :node="item" :level="0"
                            @node-click="handleMenuClick">
                        <template #label="{ node }">
                            <span v-if="node.children && node.children.length > 0">{{ node.label }}</span>
                            <span v-else>{{ node.label }} 绿波带</span>
                        </template>
                        </MenuItem>
                    </TechTabPane>
                    <TechTabPane label="特勤" name="specialDuty">
                    </TechTabPane>
                </TechTabs>
            </div>
        </template>

        <template #right>
            <!-- 模式切换按钮组 -->
            <div class="mode-switch" v-if="activeLeftTab === 'crossing'">
                <ButtonGroup v-model="currentView" :options="viewOptions" @select="onViewSelect" />
            </div>
            <!-- 特勤右上角表格 -->
            <TechTable ref="dutyTable" :columns="tableColumns" :data="tableData" class="duty-table" v-if="activeLeftTab === 'specialDuty'">

                <template #level="{ row }">
                    <span :title="row.level" :style="{ color: row.level === '二级' ? '#FFDF0C' : '#F00' }">
                        {{ row.level }}
                    </span>
                </template>

                <template #status="{ row }">
                    <span :title="row.status" :style="{ color: row.status === '进行中' ? '#FFDF0C' : '#F00' }">
                        {{ row.status }}
                    </span>
                </template>

                <template #action="{ row }">
                    <span class="action-btn" @click="handleSpecialTaskView(row)">
                        查看
                    </span>
                </template>

            </TechTable>
        </template>

        <template #center>

        </template>

    </DashboardLayout>
</template>

<script>
import DashboardLayout from '@/layouts/DashboardLayout.vue';
import DateTimeWidget from '@/components/ui/DateTimeWidget.vue';
import TechTabs from '@/components/ui/TechTabs.vue';
import TechTabPane from '@/components/ui/TechTabPane.vue';
import TongzhouTrafficMap from '@/components/TongzhouTrafficMap.vue';
import MenuItem from '@/components/ui/MenuItem.vue';
import ButtonGroup from '@/components/ui/ButtonGroup.vue';
import TechTable from '@/components/ui/TechTable.vue';
import CrossingListPanel from '@/components/ui/CrossingListPanel.vue';
import { apiGetTongzhouMenuTree, apiGetTasks, apiGetTrafficTimeSpace, apiGetCrossingTopCharts, apiGetSpecialTaskMonitorData, apiGetOverviewTopCharts } from '@/api';


export default {
    name: "HomePage",
    components: {
        DashboardLayout,
        DateTimeWidget,
        TechTabs,
        TechTabPane,
        TongzhouTrafficMap,
        MenuItem,
        ButtonGroup,
        TechTable,
        CrossingListPanel
    },
    data() {
        return {
            // 左侧边栏数据
            activeLeftTab: 'overview',
            menuData: [],
            // 地图模式切换数据
            currentView: 'map-mode',
            viewOptions: [
                { label: '列表模式', value: 'list-mode' },
                { label: '地图模式', value: 'map-mode' },
            ],
            // 1. 表头
            tableColumns: [
                { label: '序号', key: 'id', width: '14%' },
                { label: '名称', key: 'name', width: '20%' },
                { label: '执行人', key: 'executor', width: '18%' },
                { label: '等级', key: 'level', width: '14%' },
                { label: '状态', key: 'status', width: '20%' },
                { label: '操作', key: 'action', width: '14%' }
            ],

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

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

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

        // 初始显示顶部图表（如果没有路由参数覆盖的话）
        if (Object.keys(this.$route.query).length === 0) {
            this.showTopChartDalogs();
        }

    },
    methods: {
        // 处理地图点击事件
        handleMapCrossingClick(mapData, lnglat) {
            console.log('父组件接收到了地图路口点击事件:', mapData, lnglat);
            // 组装模拟数据
            let nodeData = {
                id: Math.floor(Math.random()*5)+1,
                label: mapData.road,
            }
            console.log(nodeData);
            if (this.activeLeftTab === 'overview') { // 总览
                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);
            }
        },
        // 模式切换
        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.showCrossingTopDialogs();
            }
        },
        // 处理tab点击
        handleTabClick(tabName) {
            console.log('父组件接收到了tab点击事件:', tabName);
            this.$refs.layout.clearDialogs(); // 清空全部弹窗
            this.crossingSelections = [];
            this.showTopChartDalogs(); // 根据当前Tab显示对应的顶部常驻图表
        },
        // 处理菜单点击
        handleMenuClick(nodeData) {
            console.log('父组件接收到了最底层路口点击事件:', nodeData);
            // 根据Tab来显示不同的弹窗内容
            if (this.activeLeftTab === 'overview') { // 总览
                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 === 'overview') { // 总览
                this.showOverviewTopDialogs();
            } else if (this.activeLeftTab === 'crossing') { // 路口
                this.showCrossingTopDialogs();
            } else if (this.activeLeftTab === 'trunkLine') { // 干线
                // TODO: 干线Tab的顶部图表
            } else if (this.activeLeftTab === 'specialDuty') { // 特勤
                // this.openDutyDetailDialog({id: 'route_' + new Date().getTime(), label: '特勤路口'});
            }
        },
        // 显示总览弹窗组
        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: 950, y: 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 showOverviewTopDialogs() {
            this.$refs.layout.openDialog({
                id: 'top-chart-overview-1',
                title: '',
                component: 'OnlineStatusTabs',
                width: 300,
                height: 160,
                center: false,
                showClose: false,
                draggable: false,
                resizable: false,
                position: { x: 630, y: 130 },
                noPadding: true,
                data: {}
            });
            this.$refs.layout.openDialog({
                id: 'top-chart-overview-2',
                title: '',
                component: 'DeviceStatusTabs',
                width: 300,
                height: 160,
                center: false,
                showClose: false,
                draggable: false,
                resizable: false,
                position: { x: 980, y: 130 },
                noPadding: true,
                data: {}
            });
        },
        // 显示路口弹窗组（多选分屏）
        showCrossingDalogs(nodeData) {
            console.log('路口多选', nodeData.id, nodeData.label);

            // 1. 已选中 → 取消选中
            const existIndex = this.crossingSelections.findIndex(c => c.id === nodeData.id);
            if (existIndex !== -1) {
                this.crossingSelections.splice(existIndex, 1);
                if (this.crossingSelections.length === 0) {
                    this.$refs.layout.handleDialogClose('crossing-multi-view');
                    return;
                }
                this.openCrossingMultiView();
                return;
            }

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

            // 3. 追加选中
            this.crossingSelections.push({ ...nodeData });

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

        openCrossingMultiView() {
            this.$refs.layout.openDialog({
                id: 'crossing-multi-view',
                title: '路口监控 (' + this.crossingSelections.length + '/' + this.maxCrossingSlots + ')',
                component: 'CrossingMultiView',
                width: 1400,
                height: 700,
                center: false,
                position: { x: 500, y: 150 },
                showClose: true,
                noPadding: true,
                enableDblclickExpand: 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();
            }
        },

        // 单个路口详情弹窗（总览双击展开等场景使用）
        showCrossingDetailDialogs(nodeData) {
            console.log('显示路口详情弹窗组', nodeData.id, nodeData.label);
            this.$refs.layout.openDialog({
                id: 'crossing_detail' + nodeData.id,
                title: nodeData.label || nodeData.name,
                component: 'CrossingDetailPanel',
                width: 1315,
                height: 682,
                center: false,
                showClose: true,
                position: { x: 500, y: 170 },
                noPadding: false,
                enableDblclickExpand: false,
                data: nodeData
            });
        },
        async showCrossingTopDialogs() {
            const chartData = await apiGetCrossingTopCharts();
            const { onlineChart, faultChart } = chartData;
            this.$refs.layout.openDialog({
                id: 'top-chart-crossing-1',
                title: '',
                component: 'RingDonutChart',
                width: 228, height: 124, center: false, showClose: false,
                draggable: false, resizable: false,
                position: { x: 730, y: 130 }, noPadding: true,
                data: onlineChart
            });
            this.$refs.layout.openDialog({
                id: 'top-chart-crossing-2',
                title: '',
                component: 'RingDonutChart',
                width: 228, height: 124, center: false, showClose: false,
                draggable: false, resizable: false,
                position: { x: 980, y: 130 }, noPadding: true,
                data: faultChart
            });
        },
        // 路口列表模式下弹窗
        handleCrossingViewDetail(rowData) {
            console.log('显示路口列表查看', rowData);
            this.showCrossingDetailDialogs(rowData);
        },
        // 显示干线弹窗组
        async showTrunkLineDalogs(nodeData) {
            console.log('显示干线弹窗组', nodeData.id, nodeData.label);
            const tsData = await apiGetTrafficTimeSpace();
            this.$refs.layout.openDialog({
                id: nodeData.id,
                title: nodeData.label,
                component: 'TrafficTimeSpace',
                width: 1000,
                height: 500,
                center: true,
                showClose: true,
                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,
                    onEndTask: () => {
                        console.log('点击了结束任务');
                        // this.$refs.layout.handleDialogClose(id);
                        panelData.taskInfo.status = '已结束';
                    }
                }
            });
        },
        handleSpecialTaskView(row) {
            console.log('查看特勤线路，当前数据：', row);
            this.openDutyDetailDialog(row);
        
        },


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

.mode-switch>div {
    width: 200px;
}
.duty-table {
    margin-top: 10px;
}
::v-deep .list-mode-panel {
    padding: 150px 30px 0 30px;
}
</style>
