<template>
    <div class="event-management-app">
        <!-- 主内容区 -->
        <main class="app-main">
            <!-- 筛选区 -->
            <div class="filter-section">
                <div class="filter-group">
                    <el-input v-model="searchQuery" placeholder="搜索事件名称" prefix-icon="el-icon-search" size="small"
                        class="search-input" @change="handleQuery"></el-input>
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        size="small"
                        class="date-range-picker"
                        @change="handleDateRangeChange"
                        clearable
                    />
                </div>

                <div class="filter-tags">
                    <span class="filter-label">状态筛选:</span>
                    <el-tag v-for="(value, key) in STATUS" :key="'status-' + key"
                        :type="statusFilter == key ? 'primary' : ''" :closable="statusFilter == key"
                        @click="statusFilter = key" @close="statusFilter = ''" class="filter-tag">
                        {{ value }}
                    </el-tag>
                </div>
                <div class="filter-tags">
                    <span class="filter-label">目标类型:</span>
                    <el-tag v-for="(value, key) in TARGET_TYPE" :key="'tool-' + key"
                        :type="aimFilter == key ? 'primary' : ''" :closable="aimFilter == key" @click="aimFilter = key"
                        @close="aimFilter = ''" class="filter-tag">
                        {{ value }}
                    </el-tag>
                </div>

                <div class="filter-tags">
                    <span class="filter-label">事件性质:</span>
                    <el-tag v-for="(value, key) in EVENT_TYPE" :key="'scene-' + key"
                        :type="eventFilter == key ? 'primary' : ''" :closable="eventFilter == key"
                        @click="eventFilter = key" @close="eventFilter = ''" class="filter-tag">
                        {{ value }}
                    </el-tag>
                </div>
            </div>
            <!-- 操作按钮 -->
             <div class="operation-btns">
                <el-button type="primary" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
             </div>
            <!-- 事件列表 -->
            <el-table :data="events" border class="event-table" @row-click="handleRowClick"
             v-loading="state.loading" 
             @selection-change="handleSelectionChange"
             ref="multipleTableRef"
             row-key="id"
                element-loading-text="加载中...">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="事件ID" sortable></el-table-column>
                <el-table-column prop="name" label="事件名称"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                        <el-tag type="primary">
                            {{ STATUS[row.status] }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="addr" label="站点区间"></el-table-column>
                <el-table-column prop="aimType" label="目标类别">
                    <template #default="{ row }">
                        {{ TARGET_TYPE[row.aimType] }}
                    </template>
                </el-table-column>
                <el-table-column prop="eventType" label="事件性质">
                    <template #default="{ row }">
                        {{ EVENT_TYPE[row.eventType] }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" text icon="el-icon-edit" size="small"
                            @click="handleRowClick(scope.row)">处理</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-section">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="state.queryParams.pageNum" :page-sizes="[10, 20, 50, 100]"
                    :page-size="state.queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="state.total"></el-pagination>
            </div>
        </main>
        <HandleDrawer ref="handleDrawerRef" @handle-query="handleQuery" />

        <!-- 图片预览弹窗 -->
        <el-dialog v-model="previewVisible" title="事件图片预览" width="90%" :fullscreen="true">
            <div class="fullscreen-preview">
                <img src="https://picsum.photos/1600/900" alt="事件大图预览" class="fullscreen-image">
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { STATUS, TARGET_TYPE,  EVENT_TYPE } from '@/constant/dict/event';
import HandleDrawer from '../monitor/components/HandleDrawer.vue';
import { EventType } from '@/@types/event'
import { get,del } from '@/api/public/basic'



interface QUERY {
    pageSize: number;
    pageNum: number;
    status?: string | number | null;
    aimType?: string | number | null;
    eventType?: string | number | null;
    createTime?: string | null;
}


// 响应式状态
const searchQuery = ref('');
const statusFilter = ref<number | string>();
const aimFilter = ref();
const eventFilter = ref();
const dateRange = ref<[Date, Date] | null>(null);
const previewVisible = ref(false);
const currentEvent = ref({});
const events = ref([]);
const handleDrawerRef = ref();
const multipleSelection = ref<any>([]);
const state = reactive({
    loading: false,
    queryParams: {
        pageSize: 10,
        pageNum: 1,
        status: null,
        aimType: null,
        eventType: null,
        createTime:null
    } as QUERY,
    eventForm: {

    },
    total: 0

})

watch(() => statusFilter.value, (val) => {
    state.queryParams = {
        ...state.queryParams,
        status: val && val !== 0 ? val : null
    }
    handleQuery()
})

watch(() => aimFilter.value, (val) => {
    state.queryParams = {
        ...state.queryParams,
        aimType: val && val !== 0 ? val : null
    }
    handleQuery()
})

watch(() => eventFilter.value, (val) => {
    state.queryParams = {
        ...state.queryParams,
        eventType: val && val !== 0 ? val : null
    }
    handleQuery()
})

// 日期范围变化处理
const handleDateRangeChange = (value: [Date, Date] | null) => {
    if (value && value.length === 2) {
        // 格式化日期为 YYYY-MM-DD HH:mm:ss
        const startTime = new Date(value[0]);
        const endTime = new Date(value[1]);
        
        // 设置开始时间为当天 00:00:00
        startTime.setHours(0, 0, 0, 0);
        // 设置结束时间为当天 23:59:59
        endTime.setHours(23, 59, 59, 999);
        
        state.queryParams.createTime = [formatDateTime(startTime), formatDateTime(endTime)].join(',');
    } else {
        state.queryParams.createTime = null;
    }
    handleQuery();
}

// 格式化日期时间
const formatDateTime = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 批量删除
const handleBatchDelete = ()=>{
    ElMessageBox.confirm('确定要删除选中的事件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        del({
            id: multipleSelection.value.map((item: any) => item.id)
        },'i5tGjoafvAY').then((res) => {
            if(res.status == 0){
                ElMessage.success('删除成功')
                handleQuery()
            }
        })
    })

}

// 选中列表项目
const handleSelectionChange = (rows: any[]) => {
    multipleSelection.value = rows
}

// 获取事件列表
const handleQuery = () => {
    state.loading = true
    get({
        ...state.queryParams,
        name: searchQuery.value ?? null,
    }, 'i5tGjoafvAY').then(res => {
        if (res.status == 0) {
            events.value = res.data?.result.map((item: EventType) => ({
                ...item,
                // fileImg: getImg(item.fileImg)
            })) || []
            state.total = res?.data.count
            state.loading = false
        }
    })
}



// 初始化数据
onMounted(() => {
    handleQuery()
});




// 分页事件处理
const handleSizeChange = (size) => {
    state.queryParams.pageSize = size;
    handleQuery()
};

const handleCurrentChange = (page) => {
    state.queryParams.pageNum = page;
    handleQuery()
};

// 行点击事件
const handleRowClick = (row) => {
    currentEvent.value = {
        ...row, "wgs84": {
            "x": 121.459669216064, // WGS84坐标X
            "y": 31.40948546, // WGS84坐标Y
        },
    }; // 深拷贝对象
    handleDrawerRef.value.show(row);
};


</script>

<style scoped lang="scss">
.event-management-app {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f7fa;
}
.operation-btns{
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.app-header {
    height: 60px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    z-index: 10;

    .logo {
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 500;
        color: #1890ff;

        i {
            margin-right: 8px;
            font-size: 22px;
        }
    }

    .user-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .username {
            color: #666;
            font-size: 14px;
        }
    }
}

.app-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
}

.filter-section {
    background-color: #fff;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .filter-group {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 16px;

        .search-input {
            width: 300px;
        }

        .date-range-picker {
            width: 340px;
        }
    }

    .filter-tags {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 12px;

        .filter-label {
            color: #606266;
            font-size: 14px;
            white-space: nowrap;
        }

        .filter-tag {
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
                transform: translateY(-2px);
            }
        }
    }
}

.event-table {
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    margin-bottom: 20px;
}

.pagination-section {
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
}

.event-detail {
    max-height: 600px;
    overflow-y: auto;
    padding-right: 10px;

    .el-form-item {
        margin-bottom: 16px;
    }

    .readonly-input {
        background-color: #f5f7fa;
        cursor: not-allowed;
    }

    .preview-container,
    .map-container {
        position: relative;
        width: 100%;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }

        img {
            width: 100%;
            display: block;
        }

        .preview-overlay,
        .map-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            text-align: center;
            opacity: 0;
            transition: opacity 0.3s;

            p {
                margin: 0;
                line-height: 1.5;
            }
        }

        &:hover .preview-overlay,
        &:hover .map-overlay {
            opacity: 1;
        }

        .map-marker {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #ff4d4f;
            font-size: 24px;
            animation: pulse 1.5s infinite;
        }
    }
}

@keyframes pulse {
    0% {
        transform: translate(-50%, -50%) scale(1);
        opacity: 1;
    }

    50% {
        transform: translate(-50%, -50%) scale(1.2);
        opacity: 0.8;
    }

    100% {
        transform: translate(-50%, -50%) scale(1);
        opacity: 1;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.fullscreen-preview {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 180px);

    .fullscreen-image {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
        border-radius: 4px;
    }
}

// 自定义滚动条样式
::v-deep .event-detail::-webkit-scrollbar {
    width: 6px;
}

::v-deep .event-detail::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::v-deep .event-detail::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 10px;
}

::v-deep .event-detail::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}
</style>