<template>
  <div>
    <div class="container">
      <div class="up-box box1">
        <div class="up-box-top">
          <span>
            <el-image style="width: 26px; height: 26px" :src="url1" />
          </span>
          <p>上传结果文件</p>
        </div>
        <div class="upload-area">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action=""
            multiple
            :limit="1"
            accept=".txt"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
          >
            <div class="upload-inline">
              <el-button class="upload-btn">选择文件</el-button>
              <div class="file-name" v-if="fileList.length">
                {{ fileList[0].name }}
              </div>
              <div class="upload-tip" v-else>
                TXT文件，大小需小于 50KB
              </div>
            </div>
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import up1 from "@/assets/img/up1.png";
import Encoding from "encoding-japanese";

const url1 = up1;
const fileList = ref<UploadUserFile[]>([]);
const fileContent = ref<string>("");

const emit = defineEmits<{
  (e: "file-content", content: string): void;
}>();

const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  const isTxt = file.name.toLowerCase().endsWith('.txt');
  
  if (!isTxt) {
    ElMessage.error("只能上传 TXT 格式的文件!");
    return false;
  }
  
  return true;
};

const handleFileChange: UploadProps["onChange"] = (file, files) => {
  if (!file.raw) return;
  
  const selectedFile = file.raw as File;
  if (!selectedFile) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    const bytes = new Uint8Array(e.target?.result as ArrayBuffer);

    let content = new TextDecoder("utf-8").decode(bytes);
    if (content.includes("�")) {
      content = Encoding.convert(bytes, {
        to: "UNICODE",
        from: "GBK",
        type: "string",
      });
    }

    fileContent.value = content;
    
    // 打印文件内容到控制台
    console.log("=== 上传的文件内容 ===");
    console.log(content);
    
    emit("file-content", content);
  };

  reader.readAsArrayBuffer(selectedFile);
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log("remove", file, uploadFiles);
  fileContent.value = "";
  console.log("文件内容已清空");
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log("preview", uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(`最多上传 1 个文件，当前已选 ${uploadFiles.length} 个`);
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`确定删除 ${uploadFile.name} 吗？`).then(
    () => true,
    () => false
  );
};


// 在 <script setup> 末尾添加
function clearFiles() {
  fileList.value = [];
  fileContent.value = "";
  console.log("✅ 文件列表已直接清空");
}

defineExpose({
  clearFiles,
});


</script>

<style scoped lang="scss">
/* 保留你原来的样式 */
.container {
  display: flex;
  gap: 20px;

  .up-box {
    height: 140px;
    width: 450px;
    border-radius: 10px;
    padding: 10px 20px 0 20px;

    .up-box-top {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      span {
        margin-right: 10px;
      }

      p {
        font-size: 18px;
        font-weight: 600;
      }
    }

    .upload-area {
      .upload-inline {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .file-name {
        color: #333;
        font-weight: 500;
        cursor: text;
      }

      .upload-tip {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .box1 {
    background: #eef2ff;
    border: 1px solid #d1d9ff;

    .up-box-top p {
      color: #6266f1;
    }

    :deep(.el-button.upload-btn) {
      background-color: #6266f1 !important;
      border-color: #6266f1 !important;
      color: #fff !important;

      &:hover {
        background-color: #4f52d1 !important;
        border-color: #4f52d1 !important;
      }
    }
  }
}
</style>