<template>
    <el-container class="container">
        <el-aside class="leftSide">
            <div class="well-data">
                <div class="well-title">微地震云工程</div>
                <div class="button-container">
                    <el-button type="primary" @click="showProjectDialog = true" :icon="DocumentAdd"
                        size="small">新建</el-button>
                    <el-button type="danger" @click="handleDelete" :icon="Delete" size="small">删除</el-button>
                </div>
                <el-table ref="microEarthQuakeRef" :data="microEarthQuakeDatas"
                    @selection-change="handleSelectionChange" style="margin: 0;padding: 0;overflow: hidden;"
                    row-key="ID" @row-click="handleRowClick">
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column label="名称" prop="LayerName" width="190px"></el-table-column>
                    <el-table-column label="操作" width="60">
                        <template #default="scope">
                            <el-tooltip content="删除" placement="top">
                                <Delete style="width: 1em;height: 1em;cursor: pointer;color:red;"
                                    @click="handleDelete" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="base-img">
                <el-tabs type="border-card" :stretch="true">
                    <el-tab-pane label="网格化成果" style="margin: 0;padding: 0;">
                        <el-table ref="seismicCalcResultRef" :data="seismicCalcResultData"
                            @selection-change="handleSeismicCalcResultSelectionChange"
                            style="width: 100%;margin: 0;padding: 0;overflow-y: auto;" row-key="Id"
                            @row-click="handleSeismicCalcResultRowClick">
                            <el-table-column type="selection" width="28"></el-table-column>
                            <el-table-column label="名称" prop="ResultName">
                            </el-table-column>
                            <el-table-column label="操作" width="60">
                                <template #default="scope">
                                    <el-tooltip content="删除" placement="top">
                                        <Delete style="width: 1em;height: 1em;cursor: pointer;color:red;"
                                            @click="handleDeleteSeismic" />
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="底图">
                        <div class="button-container">
                            <el-button type="success" plain @click="showBaseDrawDialog = true" :icon="Management"
                                size="small">管理底图</el-button>
                            <el-button type="success" plain @click="handleApplyBaseDraw" size="small"
                                :icon="DocumentCopy">应用底图</el-button>
                        </div>
                        <el-table ref="baseDrawRef" :data="baseDrawData"
                            @selection-change="handleBaseDrawSelectionChange"
                            style="width: 100%;margin: 0;padding: 0;overflow-y: auto;" row-key="MapID"
                            @row-click="handleBaseDrawRowClick">
                            <el-table-column type="selection" width="40"></el-table-column>
                            <el-table-column label="名称" prop="MapName"></el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-aside>
        <el-main class="main">
            <div class="scrollable-container">
                <WellRecommend />
            </div>
        </el-main>
        <ProjectEditDialog @changeShowDialog="handleChangeShowProjectDialog" :showDialog="showProjectDialog"
            v-model="showProjectDialog" :moduleId="moduleId" />
        <BaseImgDialog @changeShowDialog="handleChangeShowBaseDrawDialog" :showDialog="showBaseDrawDialog"
            v-model="showBaseDrawDialog" :moduleId="moduleId" :dataId="12" />
    </el-container>
</template>
<script setup>
definePageMeta({
    requiresAuth: true
});
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Refresh, Delete, Switch, DocumentAdd, Management, DocumentCopy } from "@element-plus/icons-vue";
import { fetchProjects, deleteProject, fetchProjectById } from '~/services/projectService'
import { fetchBaseDraws } from '~/services/baseDrawService'
import { addBaseMapData, fetchProjectBaseMapList } from '~/services/projectBaseMapService'
import { emitter } from "~/utils/eventBus";
import { ElMessageBox } from 'element-plus';
const { $toastMessage } = useNuxtApp();
import { generateGUID } from "~/utils/common";

let moduleId = "61";
let currentProjectIdKey = "currentProjectId";

let tokenKey = 'microEarthQuake-token';

const microEarthQuakeRef = ref(null);
const baseDrawRef = ref(null);
const microEarthQuakeDatas = ref([]);
const baseDrawData = ref([]);
const selectedMicroEarthQuakeRows = ref([]);
const selectedBaseDraws = ref([]);
const showBaseDrawDialog = ref(false);
const showProjectDialog = ref(false);

const seismicCalcResultRef = ref(null);
const seismicCalcResultData = ref([]);
const selectedSeismicCalcRows = ref([]);

const currentToken = computed(() => localStorage.getItem("drawerToken"));

/** 默认项目参数 */
const defaultProjectParameter = reactive({
    /** 井轨迹 */
    drawTrack: true,
    /** 关节点 */
    drawPoint: true,
    /** 显示方式(柱子，曲线) */
    drawGradient: false,
    /** 分段 */
    drawStage: true,
    /** 参数值 */
    drawParamText: true,
    /** 名称大小 */
    stageTextSize: 10,
    /** 文字大小 */
    paramTextSize: 5,
    /** 分段宽度 */
    stageWidth: 20,
    /** 高度 */
    columnHeighFactor: 10,
    /** 宽度 */
    pillarWidth: 10,
});

const currentProject = reactive({
    Id: 0,
    drawId: "",
    layerName: "",
    layerAlias: "",
    drawerFileName: "",
    /** 绘制参数配置 */
    projectParameter: { ...defaultProjectParameter },
    /** 工程权限 */
    auth: {},
});

// 控制创建项目弹出框
const handleChangeShowProjectDialog = (val) => {
    showProjectDialog.value = val;
}

const handleChangeShowBaseDrawDialog = (val) => {
    showBaseDrawDialog.value = val;
};


const loadData = async () => {
    try {
        selectedMicroEarthQuakeRows.value = [];
        const response = await fetchProjects(moduleId);
        if (!response) {
            //   $toastMessage.error("获取井数据失败");
            return;
        }
        console.log("得到微地震云数据列表：", response);
        microEarthQuakeDatas.value = response;
        const projId = localStorage.getItem(currentProjectIdKey);
        if (projId) {
            const proj = microEarthQuakeDatas.value.find(w => w.ID == projId);
            if (proj) {
                microEarthQuakeRef.value.toggleRowSelection(proj, true);
            }
        }
    } catch (error) {
        console.error('获取微地震云数据异常：', error);
        $toastMessage.error('获取微地震云数据失败！');
    }
};

// 加载底图数据
const loadBaseDraws = async () => {
    try {
        const response = await fetchBaseDraws(moduleId);
        if (!response) {
            return;
        }

        baseDrawData.value = response;
    } catch (error) {
        console.error('获取底图数据异常：', error);
        $toastMessage.error('获取底图数据失败！');
    }
};

// 加载项目所应用的底图数据
const loadProjectBaseDraws = async (projectId) => {
    let baseDraws = await fetchProjectBaseMapList(moduleId, projectId);
    if (!baseDraws) {
        return;
    }
    baseDraws.forEach(item => {
        // if (baseDrawData.value.some(d => d.MapID === item.MapId)) {
        let data = baseDrawData.value.find(d => d.MapID === item.MapId);
        if (data) {
            baseDrawRef.value.toggleRowSelection(data, true);
        };
    });
};

// 加载网格化数据
const loadMicroSeismicResult = async () => {
    seismicCalcResultData.value = null;
    if (currentProject.Id === 0) {
        return;
    }
    let meshData = await MicroSeismicCalclist(currentProject.Id);
    console.log("查询到网格化的数据：", meshData);
    if (meshData && meshData instanceof Array) {
        // seismicCalcSourceData.value = meshData;
        const handledData = meshData.map((item) => ({
            Id: item.Meshing.Id,
            ResultName: item.Pretreatment.Project_Name,
            OutGraphicFile: item.Meshing.OutGraphicFile,
            Data: item,
        }));
        seismicCalcResultData.value = handledData;
    }
};

// 删除网格化成果
const handleDeleteSeismic = async () => {
    if (selectedSeismicCalcRows.value.length === 0) {
        $toastMessage.warning("请选择要删除的成果！");
        return;
    }

    ElMessageBox.confirm(`您确定要删除选中的数据吗?`, "删除确认", {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(async () => {
            // const selectKeys = selectedSeismicCalcRows.value.map(item => item.ID);
            // try {
            //     const response = await deleteProject(moduleId, selectKeys.join(','));
            //     console.log("删除结果：", response);
            //     if (response.ok) {
            //         await loadData();
            //         emitter.emit("clearCanvas");
            //         $toastMessage.info("删除数据成功！");
            //         selectedWellRows.value = [];
            //     } else {
            //         $toastMessage.error("删除失败！");
            //     }
            // } catch (error) {
            //     $toastMessage.error("删除异常！");
            //     console.error("删除异常：", error);
            // }
        })
        .catch(() => {
            console.log("已取消删除！");
        });
};

// 获取选中项
const handleSelectionChange = (selection) => {
    selectedMicroEarthQuakeRows.value = selection;
    console.log("选择的工程：", selection);
}

const handleBaseDrawSelectionChange = (selection) => {
    selectedBaseDraws.value = selection;
    console.log("选择的底图：", selection);
};

const handleSeismicCalcResultSelectionChange = (selection) => {
    selectedSeismicCalcRows.value = selection;
    console.log("选中的网格化成果：", selection);
};


// 行点击
const handleRowClick = async (item) => {
    clearSelection("well");
    clearSelection("basedraw");
    clearSelection("seismic");
    emitter.emit("evtType", { type: 'clearCanvas', data: JSON.stringify({ drawerToken: generateGUID() }) });
    microEarthQuakeRef.value.toggleRowSelection(item, true);
    let data = null;
    if (selectedMicroEarthQuakeRows.value) {
        data = await fetchProjectById("MicroBaseMap", moduleId, item.ID);

        currentProject.Id = data.ID;
        currentProject.drawId = data.DrawId;
        currentProject.drawerFileName = data.DrawerFileName;
        currentProject.layerAlias = data.LayerAlias;
        currentProject.layerName = data.LayerName;
        // currentProject.projectParameter.drawTrack = data.projectParameter.DrawTrack;
        // currentProject.projectParameter.drawPoint = data.projectParameter.DrawPoint;
        // currentProject.projectParameter.drawGradient = data.projectParameter.DrawGradient;
        // currentProject.projectParameter.drawStage = data.projectParameter.DrawStage;
        // currentProject.projectParameter.drawParamText = data.projectParameter.DrawParamText;
        // currentProject.projectParameter.stageTextSize = data.projectParameter.StageTextSize;
        // currentProject.projectParameter.paramTextSize = data.projectParameter.ParamTextSize;
        // currentProject.projectParameter.pillarWidth = data.projectParameter.PillarWidth;
        // currentProject.projectParameter.stageWidth = data.projectParameter.StageWidth;
        // currentProject.projectParameter.columnHeighFactor = data.projectParameter.ColumnHeighFactor;

        if (data.ID) {
            localStorage.setItem(currentProjectIdKey, data.ID);
        }

        emitter.emit("seismicParam", { projId: currentProject.Id, params: null });
        // 选择对应的底图
        await loadProjectBaseDraws(item.ID);
        await loadMicroSeismicResult(item.ID);
    }
};

const handleBaseDrawRowClick = async (item) => {
    // clearSelection("basedraw");
    baseDrawRef.value.toggleRowSelection(item);
};

const handleSeismicCalcResultRowClick = async (item) => {
    // emitter.emit("evtType", { type: 'clearCanvas', data: JSON.stringify({ drawerToken: generateGUID() }) });
    clearSelection("seismic");
    seismicCalcResultRef.value.toggleRowSelection(item, true);
    const selectData = selectedSeismicCalcRows.value[0];
    // console.log("handleSeismicCalcResultRowClick 选中的网格数据：", selectData, selectData.OutGraphicFile);
    emitter.emit("evtType", { type: 'openFile', data: JSON.stringify({ fileName: selectData.OutGraphicFile, drawerToken: generateGUID() }) });
    emitter.emit("seismicParam", { projId: currentProject.Id, params: selectData.Data });
}

// 清空所选
const clearSelection = (val) => {
    console.log("清空选择：", val);
    switch (val) {
        case "well":
            if (selectedMicroEarthQuakeRows.value) {
                selectedMicroEarthQuakeRows.value.forEach(item => {
                    microEarthQuakeRef.value.toggleRowSelection(item, false);
                });
            }
            break;
        case "basedraw":
            if (selectedBaseDraws.value) {
                selectedBaseDraws.value.forEach(item => {
                    baseDrawRef.value.toggleRowSelection(item, false);
                });
            }
            break;
        case "seismic":
            if (selectedSeismicCalcRows.value) {
                selectedSeismicCalcRows.value.forEach(item => {
                    seismicCalcResultRef.value.toggleRowSelection(item, false);
                });
            }
            break;
    }
};

/** 应用底图 */
const handleApplyBaseDraw = async () => {
    console.log('应用底图：', currentProject);
    if (currentProject.Id > 0) {
        let mapIds = [];
        let mapNames = [];
        selectedBaseDraws.value.forEach((item) => {
            mapIds.push(item.MapID);
            mapNames.push(item.MapName);
        });
        let result = await addProjectBaseMap(mapIds.join(","), mapNames.join(","));

        if (result) {
            $toastMessage.success(`底图应用成功`);
        }
        else {
            $toastMessage.warning(`底图应用出错了`);
        }
        emitter.emit("evtType", { type: 'viewAll', data: JSON.stringify({ drawerToken: currentToken.value }) });
    } else {
        $toastMessage.warning("未选择工程");
        return;
    }
};

/**
     * 添加微地震云项目底图
     * @returns {Promise<void>}
     */
const addProjectBaseMap = async (mapId, mapName) => {
    const projectMapParam = {
        DrawId: currentToken.value,
        ClientId: currentToken.value,
        Module_Id: moduleId,
        Project_Id: currentProject.Id,
        Map_Id: mapId,
        Map_Name: mapName
    };
    try {
        console.info("添加底图参数:", projectMapParam);
        let result = await addBaseMapData(projectMapParam);
        if (!result) {
            $toastMessage.error("添加底图失败");
            return;
        }

        //  await loadBaseDraws();
        return result;
    }
    catch (error) {
        console.error('添加底图失败:', error);
        $toastMessage.error("添加底图失败");
        return;
    }
};

// 删除数据
const handleDelete = async () => {
    if (selectedMicroEarthQuakeRows.value.length === 0) {
        $toastMessage.warning("请选择要删除的文件！");
        return;
    }

    ElMessageBox.confirm(`您确定要删除选中的数据吗?`, "删除确认", {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(async () => {
            const selectKeys = selectedMicroEarthQuakeRows.value.map(item => item.ID);
            try {
                const response = await deleteProject(moduleId, selectKeys.join(','));
                console.log("删除结果：", response);
                if (response.ok) {
                    await loadData();
                    emitter.emit("clearCanvas");
                    $toastMessage.info("删除数据成功！");
                    selectedMicroEarthQuakeRows.value = [];
                } else {
                    $toastMessage.error("删除失败！");
                }
            } catch (error) {
                $toastMessage.error("删除异常！");
                console.error("删除异常：", error);
            }
        })
        .catch(() => {
            console.log("已取消删除！");
        });
};

onMounted(async () => {
    nextTick();
    await loadData();
    await loadBaseDraws();
    handleConfirmAdd();

    emitter.on("updateBaseDraw", async () => {
        await loadBaseDraws();
        let projId = localStorage.getItem(currentProjectIdKey);
        if (projId) {
            await loadProjectBaseDraws(projId);
        };
    });

    emitter.on("seismicCalcFinished", async () => {
        console.log("seismicCalcFinished", currentProject.Id);
        await loadMicroSeismicResult(currentProject.Id);
    });
});

const handleConfirmAdd = () => {
    emitter.on("confirmAddProject", async (data) => {
        if (data.moduleId === moduleId) {
            currentProject.drawId = data.token;
            showProjectDialog.value = false;
            await loadData();
        };
    });
};

onBeforeUnmount(() => {
    emitter.off("confirmAddProject");
    emitter.off("updateBaseDraw");
    emitter.off("seismicCalcFinished");
})
</script>
<style scoped>
/* .el-container {
    background-color: white;
    color: black;
    min-height: 800px;
    height: calc(100vh - 80px);
    margin: 0;
    padding: 0;
    overflow: hidden;
} */

.el-aside,
.el-main {
    background-color: white;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.scrollable-container {
    height: 100%;
    overflow-y: auto;
    /* border: 1px solid #ddd; */
    width: 100%;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
}

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

.well-data {
    width: 100%;
    height: 50%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border: solid 1px #5399ff;
    padding-left: 5px;
    /* overflow: hidden; */
    /* padding: 5px; */
}

.well-title {
    color: #5399ff;
    justify-content: center;
    width: 100%;
    height: 30px;
    text-align: center;
}

.base-img {
    width: 100%;
    height: 50%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border: solid 1px #5399ff;
    padding: 5px;
}

.button-container {
    display: flex;
    margin-bottom: 5px;
    height: 35px;
}

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

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