<template>
    <el-dialog v-model="visible" title="底图管理" @close="handleClose" width="800px">
        <input type="file" ref="fileInput" @change="handleFileChange" v-show="false" accept=".kev,.dfd,.pcg,.gdbx,.jpg,.xls,.xlsx,.kev,.txt" />        
        <el-tag type="primary" style="margin-bottom: 5px;">可选择kev,dfd,pcg等文件。</el-tag>
        <div>           
            <el-button type="primary" @click="triggerFileSelect">选择文件</el-button>
            <!-- 文件名回显 -->
            <span v-if="fileName" style="margin-left: 10px; color: #333">已选择文件：{{ fileName }}</span>
        </div>         
       <div class="oper">
             <el-button type="primary" :icon="Upload" @click="handleConfirm">上传底图</el-button>
        </div>
        <div>
        <el-table :data="baseDrawData">           
            <el-table-column label="图件名" Align="center" prop="MapName" width="680px">
            </el-table-column>
            <el-table-column label="操作" Align="center" width="75px">
            <template #default="scope">
                <el-popconfirm title="确认删除吗？" confirm-button-text="确认删除" cancel-button-text="取消" :popper-style="{ width: '200px' }"  @confirm="removeBaseDraw(scope.row)">
                <template #reference>
                    <el-button size="small" type="danger">
                    删除
                    </el-button>
                </template>
                </el-popconfirm>
            </template>
            </el-table-column>
        </el-table>
        </div>
          <!-- <div>
            <input type="file" @change="handleFileUpload">
            <button @click="submitFile">上传</button>
          </div> -->
      <!-- <template #tips>
        <el-tag type="primary">可选择kev,dfd,pcg等文件。</el-tag>
      </template> -->
    
</el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { Upload } from "@element-plus/icons-vue";
import { emitter } from "~/utils/eventBus";
import { ElMessageBox } from 'element-plus';
const { $toastMessage } = useNuxtApp();
import { generateGUID } from "~/utils/common";
import { fetchBaseDraws } from '~/services/baseDrawService'
import { uploadData,deleteData } from '~/services/dataManageService'
import { number } from 'echarts';


// const selectedWells = computed(()=>{selectedWellRows.value.map(row => row.JH)});

const props = defineProps({
    showDialog: {
        type: Boolean,
        default: false,
        required: true
    },
    moduleId: {
        type: String,
        required: true
    },
    dataId: {
        type: Number,
        required: true
    }
});

const visible = ref(props.showDialog);
const fileInput = ref(null);
const baseDrawData = ref([]);
const fileName = ref("");
const selectedFile = ref(null);

const emit = defineEmits(['update:changeShowDialog']);


const handleClose = () => {
    visible.value = false;
    fileName.value = "";
    emit("update:changeShowDialog", false);
};

const triggerFileSelect = () => {
    fileInput.value.click();
};

// 删除底图
const removeBaseDraw = async (data) => {
    console.log("删除底图：", data);
    const response = await deleteDataFile(data.id);
    $toastMessage.success("删除成功！");
    await loadBaseDraws();
};

// 调用删除文件API
const deleteDataFile = async (id) => {
    try {
        const response = await deleteData(props.dataId, id); // 假设 deleteData 是你的 API 方法
        if (response.status !== 200) {
            $toastMessage.error("删除失败！");
            return;
        }
        return 1; // 返回 1 表示删除成功
    } catch (error) {
        console.error("删除失败:", error);
        $toastMessage.error("删除失败！");
        return 0; // 返回 0 表示删除失败
    }
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查是否是 Excel 文件
    const fileExtension = file.name.split(".").pop().toLowerCase();
    if (
      fileExtension === "kev" ||
      fileExtension === "dfd" ||
      fileExtension === "gdbx" ||
      fileExtension === "pcg" ||
      fileExtension === "xls" ||
      fileExtension === "xlsx" ||
      fileExtension === "txt" ||
      fileExtension === "jpg"
    ) {
      fileName.value = file.name; // 设置文件名
      selectedFile.value = file;
    } else {
      $toastMessage.warning("请选择一个有效的[Excel, GDBX, DFD, PCG, KEV, TXT]格式文件！");
      return;
    }
  }
};

// 加载底图数据
const loadBaseDraws = async () => {
    try {
        const response = await fetchBaseDraws(props.moduleId);
        if (!response) {
            return;
        }
        console.log("底图数据：", response);
        baseDrawData.value = response;
    } catch (error) {
        console.error('获取底图数据异常：', error);
        $toastMessage.error('获取底图数据失败！');
    }
};

const handleConfirm = async () => {
    if (!selectedFile.value) {
        $toastMessage.warning("请选择文件！");
        return;
    }
    const formData = new FormData();
    formData.append("File", selectedFile.value);
    formData.append("DataId", props.dataId);
    try {
        await uploadData(formData);
        $toastMessage.success("上传成功！");
        await loadBaseDraws();
        emitter.emit("updateBaseDraw");
    } catch (error) {
        console.error("上传文件失败！", error);
        $toastMessage.error("上传失败！");
    };
};

onMounted(async() => {
    await nextTick();
    await loadBaseDraws();
});
</script>
<style scoped>

.tabs{
    margin: 0;
    padding:0;
     border: solid 1px #ccc;
}

.param-table {
    width: 100%;
    overflow: auto;
    height: 500px;
    border: solid 1px #ccc;
    margin: 0;
    padding: 0;
}

.oper{
    display: flex;
    justify-content: right;
    flex-flow: inline-end;
    margin-top: 15px;
}
</style>