<template>
    <el-container class="container">
        <el-aside class="data-tree">
            <div class="oper">
                <el-button type="primary" :icon="Refresh" @click="handleSetDrawParam(true)">设置勾绘参数</el-button>
                <el-button v-show="true" type="danger" style="margin-left: 36px;" :disabled="!isDeleteEnabled"
                    @click="handleDeleteSelected">删除</el-button>
            </div>
            <div class="scrollable-container">
                <el-table ref="drawResults" :data="resultData" @selection-change="updateSelectedResults" width="280"
                    row-key="ParamName" @row-click="handleRowClick">
                    <el-table-column type="selection" :selectable="isSelectable" width="40" fixed></el-table-column>
                    <el-table-column prop="ParamName" label="名称" width="*" show-overflow-tooltip>
                        <template #default="scope">
                            <el-link @click="handleOpenFile(scope.row)">
                                <div :style="{ padding: '0' }">{{ scope.row.ParamName }}</div>
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="State" label="状态" width="70">
                        <template #default="scope">
                            <span :style="{ color: getStateColor(scope.row.State) }">{{
                                getStateText(scope.row.State) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                        <template #default="scope">
                            <el-tooltip content="删除" placement="top" :disabled="scope.row.State === 1">
                                <Delete style="width: 1em;height: 1em;color:red;cursor: pointer;"
                                    @click="handleDelete(scope.row)" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-aside>
        <el-main class="main">
            <WellRecommend :tokenKey="currentTokenKey" :showRight="false" />
        </el-main>
    </el-container>
    <DrawParamDialog @changeShowSetParam="handleSetDrawParam" :showSetParam="showParamDialog" v-model="showParamDialog"
        class="draw-param-dialog" />
    <ProgressTracker ref="progressRef" v-model="progressVisible" title="计算进度" :initialProgress="currentProgress"
        message="正在计算……" @complete="onComplete" />
</template>
<script setup>
definePageMeta({
    requiresAuth: true
});
import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { Refresh, Delete, View } from "@element-plus/icons-vue";
import { emitter } from "~/utils/eventBus";
import { ElMessageBox } from 'element-plus';
const { $toastMessage } = useNuxtApp();
import { generateGUID } from "~/utils/common";
import { fetchFlatResultData, fetchRefreshResult, deleteFlatResults } from '~/services/drawParamService'
import { STORAGE_KEYS } from "~/utils/storageKeys"
import { EMIT_COMMAND } from '~/utils/commandTypes';
// 当前页图件token的 key
const currentTokenKey = STORAGE_KEYS.DRAW_PARAM_IMG_TOKEN;

const showParamDialog = ref(false);
// 实时刷新结果
const refreshTimer = ref(null);
const resultData = ref([]);
const isDeleteEnabled = ref(false);
const selectedResultRows = ref([]);
const showDeleteDialog = ref(false);
const drawResults = ref(null);

const progressRef = ref(null);
const progressVisible = ref(false);
const currentProgress = ref(0);

const updateSelectedResults = (val) => {
    selectedResultRows.value = val;
    if (val.length > 0) {
        isDeleteEnabled.value = true;
    } else {
        isDeleteEnabled.value = false;
    }
};

// 获取结果
const getResults = async () => {
    try {
        const response = await fetchFlatResultData();
        if (response) {
            // resultData.value = response;
            resultData.value.splice(0, resultData.value.length, ...response);
        }
    } catch (error) {
        console.error("获取结果数据失败:", error);
        // 如果连续多次获取失败，可以考虑停止自动刷新
    }
};

// 行点击
const handleRowClick = async (item) => {
    if (item.State === 0) {
        return;
    }
    else if (item.State === 1) {
        emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
        clearSelection();
        drawResults.value.toggleRowSelection(item, true);
    }
};

// 打开结果文件
const handleOpenFile = (item) => {
    try {
        if (item.State === 0) {
            $toastMessage.info("正在生成中……");
            return;
        }
        else if (item.State === 1) {
            clearSelection();
            let fileUrl = item.AreaId + '/' + item.ParamName + '.kev';
            emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.OPEN_FILE, cmdID: currentTokenKey, data: JSON.stringify({ fileName: fileUrl, drawerToken: generateGUID() }) });
            drawResults.value.toggleRowSelection(item, true);
        } else {
            $toastMessage.error("生成失败！");
            return;
        }
    } finally {
        emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
    }
}

const clearSelection = () => {
    if (selectedResultRows.value) {
        selectedResultRows.value.forEach(item => {
            drawResults.value.toggleRowSelection(item, false);
        });
    }
    // drawResults.value.toggleAllSelection(false);
    // drawResults.value.toggleAllSelection();
};

const handleSetDrawParam = (val) => {
    showParamDialog.value = val;
};

const isSelectable = (row) => {
    // 如果该行的状态为 "生成中" (State === 0)，则不允许选择
    return row.State !== 0;
};

const getStateText = (state) => {
    switch (state) {
        case 0: return "生成中";
        case 1: return "成功";
        case 2: return "失败";
        default: return "错误";
    }
};

const getStateColor = (state) => {
    switch (state) {
        case 0: return "orange";
        case 1: return "green";
        case 2: return "red";
        default: return "gray";
    }
};

// 添加一个启动自动刷新的函数
const startAutoRefresh = () => {
    // 如果已经有定时器在运行，先清除它
    if (refreshTimer.value) {
        clearInterval(refreshTimer.value);
        refreshTimer.value = null;
    }

    // 设置新的定时器，每5秒刷新一次结果
    refreshTimer.value = setInterval(async () => {
        await getResults();

        const totalCount = resultData.value.length;
        const finished = resultData.value.filter(item => item.State !== 0).length;
        currentProgress.value = parseFloat((finished / totalCount) * 100).toFixed(2);

        // 检查是否所有任务都已完成
        const hasRunningTasks = resultData.value.some(item => item.State === 0);

        // 如果没有正在运行的任务，可以降低刷新频率或停止刷新
        if (!hasRunningTasks && refreshTimer.value) {
            clearInterval(refreshTimer.value);
            // 降低频率继续刷新（每15秒一次）或完全停止
            // refreshTimer.value = setInterval(getResults, 15000);
        }
    }, 5000);
};

const handleDeleteSelected = () => {
    ElMessageBox.confirm(`您确定要删除所选数据吗?`, "删除确认", {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
    }).then(async () => {
        if (selectedResultRows.value) {
            const paramNames = selectedResultRows.value.map(item => item.ParamName);
            if (paramNames.length > 0) {
                await deleteFlatResults(paramNames);
                await getResults();
            }
        }
    }).catch(() => {
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm(`您确定要删除所选数据吗?`, "删除确认", {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
    }).then(async () => {
        if (row) {
            const paramNames = [];
            paramNames.push(row.ParamName);
            if (paramNames.length > 0) {
                await deleteFlatResults(paramNames);
                await getResults();
            }
        }
    }).catch(() => {
    });
}

onMounted(async () => {
    nextTick();
    await getResults();

    await onConfirmDraw();

    // 添加初始化时的自动刷新机制
    // startAutoRefresh();
});

const onConfirmDraw = async () => {
    emitter.on(EMIT_COMMAND.CONFIRM_DRAW, (data) => {
        showParamDialog.value = false;
        progressVisible.value = true;

        data.forEach(item => {
            const paramName = item.PillarName;
            const existingRecord = resultData.value.find(item => item.ParamName === paramName);
            if (existingRecord) {
                existingRecord.State = 0;
            } else {

                // const workArea = localStorage.getItem(STORAGE_KEYS.GLOBAL_WORK_AREA);
                // console.log("工区：", workAreaStr)
                // let areaId = '1';
                // if (workAreaStr) {
                //     const workarea = JSON.parse(workAreaStr);
                //     areaId = workarea?.AreaID || '1';
                // }

                resultData.value.push({
                    AreaId: '1',
                    ParamName: paramName,
                    State: 0
                });
            }
        });
        startAutoRefresh();
    });
};

onUnmounted(() => {
    if (refreshTimer.value) {
        clearInterval(refreshTimer.value);
    }
});

onBeforeUnmount(() => {
    emitter.off(EMIT_COMMAND.CONFIRM_DRAW);
})

const onComplete = () => {
    // progressRef.value.close();
    $toastMessage.success("计算完成！");
}

</script>
<style scoped>
.data-tree {
    padding-top: 10px;
    width: 280px;
    border: solid 1px #ccc;
    overflow-y: auto;
    overflow-x: hidden;
}

.main {
    display: inline;
    width: 100%;
    height: 100%;
    padding: 0;
}

.draw-param-dialog {
    width: calc(100% - 300px);
    min-width: 800px;
    height: calc(100vh - 500px);
    min-height: 500px;
    z-index: 1002;
}

.oper {
    width: 100%;
    height: 40px;
    margin: 0;
    padding-left: 10px;
    border-bottom: solid 1px #ccc;
}
</style>
