<template>
    <div class="container">
        <div 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="handleDelete">删除</el-button>
            </div>
            <div class="scrollable-container">
                <el-table ref="drawResults" :data="resultData" @selection-change="updateSelectedResults" width="300"
                    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="110" fixed></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 @click="refreshResult(scope.row)" :disabled="scope.row.State === 1" content="查看" placement="top">
                            <View size="small" style="width: 1em;height: 1em;color:green;margin-right:8px;cursor: pointer;" type="primary"/>
                        </el-tooltip> -->
                            <el-tooltip content="删除" placement="top" :disabled="scope.row.State === 1">
                                <Delete style="width: 1em;height: 1em;color:red;cursor: pointer;"
                                    @click="handleDelete" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="main">
            <WellRecommend />
        </div>
    </div>
    <DrawParamDialog @changeShowSetParam="handleSetDrawParam" :showSetParam="showParamDialog" v-model="showParamDialog"
        class="draw-param-dialog" />
</template>
<script setup>
definePageMeta({
    requiresAuth: true
});
import { ref, onMounted, onUnmounted } 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, deleteResult } from '~/services/drawParamService'

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 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) => {
    console.log("行点击：", item);
    if (item.State === 0) {
        $toastMessage.info("正在生成中……");
        return;
    }
    else if (item.State === 1) {
        clearSelection();
        let fileUrl = item.AreaId + '/' + item.ParamName + '.kev';
        emitter.emit("evtType", { type: 'openFile', data: JSON.stringify({ fileName: fileUrl, drawerToken: generateGUID() }) });
        drawResults.value.toggleRowSelection(item, true);
    } else {
        $toastMessage.error("生成失败！");
        return;
    }

};

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 () => {
        console.log("自动刷新结果数据...");
        await getResults();

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

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

const refreshResult = async (row) => {
    // startLoading();
    try {
        // 假设有一个刷新接口 fetchRefreshResult，接受 ParamName 或 ID
        const response = await fetchRefreshResult(row.ParamName);
        console.log("刷新结果:", response);
        // 更新数据行的状态
        row.State = response.State; // 假设后台返回新的状态
    } finally {
        // stopLoading();
    }
};

// 单个删除
// const handleDeleteRow = async (row) => {
//     // console.log('删除数据：', row);
//     // selectedResultRows.value.push(row);
//     handleDelete();
// };

const handleDelete = () => {
    // console.log("要删除的数据：", selectedResultRows.value);

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

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

    await onConfirmDraw();

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

const onConfirmDraw = async () => {
    emitter.on('confirmDraw', (data) => {
        showParamDialog.value = false;
        console.log("确定勾绘的参数：", data);
        data.forEach(item => {
            const paramName = item.PillarName;

            console.log('参数名：', paramName);
            const existingRecord = resultData.value.find(item => item.ParamName === paramName);
            if (existingRecord) {
                existingRecord.State = 0;
            } else {
                const workarea = JSON.parse(localStorage.getItem('workarea'));
                resultData.value.push({
                    AreaId: workarea.AreaID,
                    ParamName: paramName,
                    State: 0
                });
            }
        });
        startAutoRefresh();
    });
};

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

</script>
<style scoped>
/* .container {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: row;
} */

.data-tree {
    padding-top: 10px;
    width: 370px;
    border: solid 1px #ccc;
    overflow-y: auto;
    overflow-x: hidden;
}

.main {
    display: inline;
    width: 100%;
}

.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>
