<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="wellDataRef" :data="wellData" @selection-change="handleSelectionChange"
                    style="width: 100%;margin: 0;padding: 0;overflow-y: auto;overflow-x: hidden;" row-key="ID"
                    @row-click="handleRowClick">
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column label="名称" prop="LayerName" width="*" show-overflow-tooltip>
                        <template #default="scope">
                            <el-link @click="handleOpenFile(scope.row)">
                                <div :style="{ padding: '0' }">{{ scope.row.LayerName }}</div>
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="55">
                        <template #default="scope">
                            <el-tooltip content="删除" placement="top">
                                <Delete style="width: 1em;height: 1em;cursor: pointer;color:red;"
                                    @click="handleDelete(scope.row)" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="base-img">
                <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" :icon="DocumentCopy"
                        size="small">应用底图</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" width="*"></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>
        </el-aside>
        <el-main class="main">
            <!-- <div class="scrollable-container"> -->
            <WellRecommend :tokenKey="currentTokenKey" />
            <!-- </div> -->
        </el-main>
    </el-container>
    <ProjectEditDialog @changeShowDialog="handleChangeShowProjectDialog" :showDialog="showProjectDialog"
        v-model="showProjectDialog" :moduleId="moduleId" />
    <BaseImgDialog @changeShowDialog="handleChangeShowBaseDrawDialog" :showDialog="showBaseDrawDialog"
        v-model="showBaseDrawDialog" :moduleId="moduleId" :dataId="10" />

    <LoadingDialog v-model="loading" ref="loadingRef" :timeout="10000" message="正在应用底图……" @timeout="onTimeout" />
</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";
import { EMIT_COMMAND } from '~/utils/commandTypes';
import { STORAGE_KEYS } from "~/utils/storageKeys"
// 当前页图件token的 key
const currentTokenKey = STORAGE_KEYS.HORIZONTAL_WELL_TOKEN;

const loading = ref(false);
const loadingRef = ref(null);

let moduleId = "51";
let currentProjectIdKey = "hw:currentProjectId";

const wellDataRef = ref(null);
const baseDrawRef = ref(null);
const wellData = ref([]);
const baseDrawData = ref([]);
const selectedWellRows = ref([]);
const selectedBaseDraws = ref([]);
const showBaseDrawDialog = ref(false);
const showProjectDialog = ref(false);

const currentToken = computed(() => localStorage.getItem(currentTokenKey));

/** 默认项目参数 */
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 onTimeout = (() => {
    $toastMessage.error("应用底图超时！");
});

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

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

const loadData = async () => {
    try {
        selectedWellRows.value = [];
        const response = await fetchProjects(moduleId);
        if (!response) {
            //   $toastMessage.error("获取井数据失败");
            return;
        }
        wellData.value = response;
        const projId = localStorage.getItem(currentProjectIdKey);
        if (projId) {
            const proj = wellData.value.find(w => w.ID == projId);
            if (proj) {
                wellDataRef.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 handleSelectionChange = (selection) => {
    selectedWellRows.value = selection;
}

const handleBaseDrawSelectionChange = (selection) => {
    selectedBaseDraws.value = selection;
};

const handleRowClick = (row) => {
    clearSelection("well");
    wellDataRef.value.toggleRowSelection(row);
}

// 行点击
const handleOpenFile = async (item) => {
    if (!item) {
        return;
    }
    emitter.emit(EMIT_COMMAND.SOURCE_CHANGED);
    handleRowClick(item);
    // clearSelection("well");
    emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.CLEAR_CANVAS, cmdID: currentTokenKey, data: JSON.stringify({ drawerToken: generateGUID() }) });

    const fileUrl = `${item.LayerName}.kev`;
    emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.OPEN_FILE, cmdID: currentTokenKey, data: JSON.stringify({ fileName: fileUrl, drawerToken: generateGUID() }) });
    // wellDataRef.value.toggleRowSelection(item, true);
    let data = await fetchProjectById("BaseMap", 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);
    }

    clearSelection("basedraw");
    // 选择对应的底图
    await loadProjectBaseDraws(item.ID);
    // TODO 打开对应的文件并显示对应的参数

    emitter.emit(EMIT_COMMAND.PROJECT_PARAM, data);

};

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

// 清空所选
const clearSelection = (val) => {
    switch (val) {
        case "well":
            if (selectedWellRows.value) {
                selectedWellRows.value.forEach(item => {
                    wellDataRef.value.toggleRowSelection(item, false);
                });
            }
            break;
        case "basedraw":
            if (selectedBaseDraws.value) {
                selectedBaseDraws.value.forEach(item => {
                    baseDrawRef.value.toggleRowSelection(item, false);
                });
            }
            break;
    }
};

/** 应用底图 */
const handleApplyBaseDraw = async () => {

    if (currentProject.Id > 0) {
        let mapIds = [];
        let mapNames = [];
        selectedBaseDraws.value.forEach((item) => {
            mapIds.push(item.MapID);
            mapNames.push(item.MapName);
        });
        try {
            loading.value = true;
            let result = await addProjectBaseMap(mapIds.join(","), mapNames.join(","));
            if (result) {
                $toastMessage.success(`底图应用成功`);
            }
            else {
                $toastMessage.warning(`底图应用出错了`);
            }
            emitter.emit(EMIT_COMMAND.EVT_TYPE, { type: EMIT_COMMAND.VIEW_ALL, cmdID: currentTokenKey, data: JSON.stringify({ drawerToken: currentToken.value }) });
        } catch (error) {
            $toastMessage.error(`底图应用出错了：${error}`);
        } finally {
            loadingRef.value.close();
        }
    } 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 {
        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 (row) => {
    if (row) {
        // selectedWellRows.value = null;
        // selectedWellRows.value.push(row);
        handleRowClick(row);
    }
    if (selectedWellRows.value.length === 0) {
        $toastMessage.warning("请选择要删除的项目！");
        return;
    }

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

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

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

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

onBeforeUnmount(() => {
    emitter.off(EMIT_COMMAND.CONFIRM_ADD_PROJECT);
    emitter.off(EMIT_COMMAND.UPDATE_BASE_DRAW);
})
</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: calc(100vh - 100px);
    overflow-y: auto;
    /* border: 1px solid #ddd; */
    width: 100%;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
}

.leftSide {
    width: 260px;
    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 #f5f5f5;
    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 #f5f5f5;
    padding: 5px;
}

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

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

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