<template>
    <el-container class="container">
        <el-aside class="leftSide">
            <div class="img-file-data">
                <div class="img-file-title">地质图件</div>
                <div class="button-container">
                    <el-dropdown @command="uploadData">
                        <el-button type="primary" :icon="Upload" size="small">导入
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <template v-slot:dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="geology">导入地质图件</el-dropdown-item>
                                <el-dropdown-item command="geologyParam">导入地质参数图件</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                    <el-button type="primary" :icon="Select" size="small"
                        @click="chooseDataVisible = true">选择图件</el-button>
                    <!-- <el-dropdown @command="handleCalc">
                        <el-button type="primary" :icon="SetUp" size="small" :disabled="calcBtnDisabled">计算
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <template v-slot:dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="calc">设置计算参数</el-dropdown-item>
                                <el-dropdown-item command="setbaseimg">设置底图</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown> -->

                </div>
                <el-table ref="imgFileRef" :data="imgFileData" @selection-change="handleSelectionChange"
                    style="width: 100%;margin: 0;padding: 0;overflow-y: auto;overflow-x: hidden;" row-key="MapID"
                    @row-click="handleRowClick" stripe>
                    <el-table-column type="selection" width="35"></el-table-column>
                    <el-table-column label="图件名称" prop="MapName" width="*" show-overflow-tooltip>
                        <template #default="{ row }">
                            <el-link @click="handleOpenFile(row)">
                                {{ row.MapName }}
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="85">
                        <template #default="scope">
                            <el-tooltip content="计算" placement="top">
                                <el-button :icon="DocumentAdd" circle type="primary" style="cursor: pointer;"
                                    size="small" @click="setParamsVisible = true" />
                            </el-tooltip>
                            <el-tooltip content="移除" placement="top">
                                <el-button :icon="Delete" type="danger" circle size="small" style="cursor: pointer;"
                                    @click="handleDelete(scope.row)" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="img-file-data">
                <div class="img-file-title">绘制成果</div>
                <div class="button-container">
                    <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteResults">删除</el-button>
                </div>
                <el-table ref="drawResultRef" :data="drawResultData" @selection-change="handleDrawResultSelectionChange"
                    style="width: 100%;margin: 0;padding: 0;overflow-y: auto;overflow-x: hidden;" row-key="MapID"
                    @row-click="handleDrawResultRowClick">
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column label="图件名称" prop="MapName" width="*" show-overflow-tooltip>
                        <template #default="{ row }">
                            <el-link @click="handleOpenResultFile(row)">{{ row.MapName }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="85">
                        <template #default="scope">
                            <el-tooltip content="设置底图" placement="top">
                                <el-button :icon="SetUp" type="primary" circle size="small" style="cursor: pointer;"
                                    @click="handleSetBaseImg(scope.row)" />
                            </el-tooltip>
                            <el-popconfirm title="确认删除吗？" confirm-button-text="确认删除" cancel-button-text="取消"
                                :popper-style="{ width: '200px' }" @confirm="handleDeleteResult(scope.row)">
                                <template #reference>
                                    <el-button :icon="Delete" size="small" circle type="danger"
                                        style="cursor: pointer;" />
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-aside>
        <el-main class="main">
            <WellRecommend :tokenKey="currentTokenKey" :showRight="false" />
        </el-main>

        <ImportDataDialog :data-id="dataId" :is-visible="importDialogVisible" @update:changeShowDialog="handleShowIDD"
            v-model="importDialogVisible" />
        <BaseDataTable :is-visible="chooseDataVisible" v-model="chooseDataVisible"
            @update:changeShowDialog="handleShowBDT" @updateSelected="handleSelectedFile" />
        <FavorableAreaCalcParam :is-visible="setParamsVisible" v-model="setParamsVisible"
            @update:changeShowDialog="handleShowFACP" @setParams="handleSetParams" />
        <LoadingDialog v-model="loading" ref="loadingRef" :timeout="20000" :message="loadingMsg" @timeout="onTimeout" />
    </el-container>
</template>
<script setup>
definePageMeta({
    requiresAuth: true
});

import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Delete, Select, Upload, SetUp, DocumentAdd } from "@element-plus/icons-vue";
import { getResults, calcFavorableArea, deleteByMapIds, deleteByRelateId, mergeFavorableArea } from '~/services/favorableAreaResultService';
import { emitter } from "~/utils/eventBus";
const { $toastMessage } = useNuxtApp();
import { generateGUID } from "~/utils/common";
import { STORAGE_KEYS } from "~/utils/storageKeys"
import { ElMessageBox } from 'element-plus';
import { COMMAND, EMIT_COMMAND } from '~/utils/commandTypes'
import { useWebSocket } from '@/composables/useWebSocket'
const config = useRuntimeConfig();
const { messages, onMessage, status, send } = useWebSocket();
// 当前页图件token的 key
const currentTokenKey = STORAGE_KEYS.FAVORABLE_AREA_TOKEN;

// 图件表格引用
const imgFileRef = ref(null);
// 图件表格数据
const imgFileData = ref([]);
// 导入数据时的数据类型
// 9: 地质图件
// 11: 地质参数图件
const dataId = ref(0);
// 导入图件弹出框显隐属性
const importDialogVisible = ref(false);
// 选择图件对话框显隐属性
const chooseDataVisible = ref(false);
// 设置值域对话框显隐属性
const setParamsVisible = ref(false);

// 进度条对象
const loadingRef = ref(null);
// 进度条显示
const loading = ref(false);
const loadingMsg = ref('正在计算有利区……');


// 当前选中的地质图件数组
const selectedImageFile = ref([]);

const drawResultRef = ref(null);
const drawResultData = ref([]);
const selectedResultRows = ref([]);

const dataDir = config.public.dataDir;

// 选择导入图件类型
const uploadData = (val) => {
    switch (val) {
        case "geology":
            dataId.value = 9;
            break;
        case "geologyParam":
            dataId.value = 11;
            break;
    };
    importDialogVisible.value = true;
};

// 导入图件对话框显隐事件
const handleShowIDD = (val) => {
    importDialogVisible.value = val;
}

// 选择图件对话框显隐事件
const handleShowBDT = (val) => {
    chooseDataVisible.value = val;
}

// 设置计算参数对话框显隐事件
const handleShowFACP = (val) => {
    setParamsVisible.value = val;
};

// 设置计算参数事件
const handleSetParams = async (par) => {
    try {
        loading.value = true;
        loadingMsg.value = "正在计算有利区……";
        const drawerToken = localStorage.getItem(currentTokenKey);
        const mapId = selectedImageFile.value[selectedImageFile.value.length - 1].MapID;
        const response = await calcFavorableArea({ SourceIds: mapId, GenParams: JSON.stringify(par), DrawerToken: drawerToken });
        if (response > 0) {
            await getFavorableResults(mapId);
        }
    } catch (error) {
        console.error("执行错误：", error);
        $toastMessage.error("执行计算时发生错误！");
        return;
    } finally {
        loadingRef.value.close();
    }
};

// 加载窗口超时
const onTimeout = () => {
    $toastMessage.error("执行计算超时，请稍后重试！");
}

// 接收选择图件对话框选中的图件
const handleSelectedFile = (data) => {
    if (data) {
        data.forEach(item => {
            const exists = imgFileData.value.find(w => w.MapID === item.MapID);
            if (!exists) {
                imgFileData.value.push(item);
            }
        });

        localStorage.setItem(STORAGE_KEYS.FAVORABLE_AREA_SELECTED_FILE, JSON.stringify(imgFileData.value));
    }
};

// 设置底图事件
const handleSetBaseImg = (row) => {
    if (!selectedImageFile.value) {
        return;
    }
    const selectedImg = selectedImageFile.value[selectedImageFile.value.length - 1];
    const mapName = selectedImg.MapName;
    const fileName = `${dataDir}/${mapName}`;
    const drawerToken = localStorage.getItem(currentTokenKey);
    loading.value = true;
    loadingMsg.value = "正在合并底图……";

    send(COMMAND.MERGE_FILE, { fileName: fileName }, drawerToken);

};

// 移除底图事件
const handleDelete = (row) => {
    imgFileData.value = imgFileData.value.filter(w => w !== row);
}

// 批量删除结果
const handleDeleteResults = async () => {
    if (selectedResultRows.value) {

        let sourceIds = [];
        selectedResultRows.value.forEach((item) => {
            sourceIds.push(item.MapID);
        });

        if (sourceIds.length === 0) {
            $toastMessage.warning("请选择要删除的绘制成果！");
            return;
        }

        ElMessageBox.confirm(`您确定要删除选中的数据吗?`, "删除确认", {
            confirmButtonText: "确认删除",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async () => {
                var response = await deleteByMapIds(sourceIds);
                if (response) {
                    $toastMessage.success("删除成功!");
                    const mapId = selectedImageFile.value[selectedImageFile.value.length - 1].MapID;
                    await getFavorableResults(mapId);
                    return;
                } else {
                    $toastMessage.error("删除失败!");
                    return;
                }
            }).catch(() => {
            });
    }
    else {
        $toastMessage.warning("请先选择要删除的文件!");
        return;
    }
}

const unsubscribe = onMessage((data) => {
    try {
        if (!data) return; // 如果没有新消息，直接返回
        const json = JSON.parse(data);
        const evtType = json.type;
        if (evtType === COMMAND.MERGE_FILE) {
            // emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: evtType, data: data });
            loadingRef.value.close();
            $toastMessage.success("合并底图完成……");
        }
    } catch (error) {
        console.error("异常：", error);
    }
});

// 删除结果文件
const handleDeleteResult = async (row) => {
    if (row) {

        let sourceIds = [];
        sourceIds.push(row.MapID);

        if (sourceIds.length === 0) {
            $toastMessage.warning("请选择要删除的绘制成果！");
            return;
        }

        var response = await deleteByMapIds(sourceIds);
        if (response) {
            $toastMessage.success("删除成功!");
            const mapId = selectedImageFile.value[selectedImageFile.value.length - 1].MapID;
            await getFavorableResults(mapId);
            return;
        } else {
            $toastMessage.error("删除失败!");
            return;
        }
    }
    else {
        $toastMessage.warning("请先选择要删除的文件!");
        return;
    }
};

// 获取有利区结果
const getFavorableResults = async (mapId) => {
    try {
        const response = await getResults(mapId);
        drawResultData.value = response;
    } catch (error) {
        console.error("获取数据失败:", error);
    }
};

// 图件表格行点击事件
const handleRowClick = async (row) => {
    if (selectedImageFile.value) {
        selectedImageFile.value.forEach((item) => {
            imgFileRef.value.toggleRowSelection(item);
        });
    }
    imgFileRef.value.toggleRowSelection(row);
};

const handleOpenFile = async (row) => {
    if (row) {
        let token = generateGUID();
        localStorage.setItem(currentTokenKey, token);
        emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
        emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.OPEN_FILE, cmdID: currentTokenKey, data: JSON.stringify({ fileName: row.MapName, drawerToken: token }) });

        await getFavorableResults(row.MapID);
    }
}

const handleOpenResultFile = async (row) => {
    if (row) {
        let token = generateGUID();
        localStorage.setItem(currentTokenKey, token);
        emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
        emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.OPEN_FILE, cmdID: currentTokenKey, data: JSON.stringify({ fileName: row.MapName, drawerToken: token }) });

    }
}

// 图件表格选中事件
const handleSelectionChange = (selection) => {
    selectedImageFile.value = selection;
};

// 结果图表选择
const handleDrawResultSelectionChange = (selection) => {
    selectedResultRows.value = selection;
};

// 结果图表行点击事件
const handleDrawResultRowClick = (row) => {
    if (selectedResultRows.value) {
        selectedResultRows.value.forEach((item) => {
            drawResultRef.value.toggleRowSelection(item, false);
        });
    }

    drawResultRef.value.toggleRowSelection(row);
};

onMounted(() => {
    imgFileData.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.FAVORABLE_AREA_SELECTED_FILE) || '[]');
});

onUnmounted(() => {
    unsubscribe();
});
</script>
<style scoped>
.scrollable-container {
    height: calc(100vh - 100px);
    overflow-y: auto;
    /* border: 1px solid #ddd; */
    width: 100%;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
}

.leftSide {
    width: 275px;
    height: calc(100vh - 55px);
    border: none;
    background-color: #333;
    display: flex;
    flex-direction: column;
    margin: 0;
    padding: 0;
}

.img-file-data {
    width: 100%;
    height: 50%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border: solid 1px #ccc;
    padding: 0;
}

.img-file-title {
    color: #5399ff;
    justify-content: center;
    width: 100%;
    height: 40px;
    text-align: center;
    background-color: rgb(245, 245, 245);
    margin: 0;
    padding: 0;
}

.button-container {
    display: flex;
    margin: 0;
    gap: 10px;
    padding-top: 5px;
    padding-left: 5px;
    padding-bottom: 5px;
    border-bottom: solid 1px #ccc;
}

.main {
    width: 100%;
    /* height: calc(100vh - 40px); */
    overflow: auto;
    margin: 0;
    padding: 0;
}

.oper {
    width: 100%;
    height: 40px;
    margin: 0;
    padding-left: 10px;
}
</style>