<template>
  <div>
    <div class="container">
      <div class="upload-card">
        <div class="card-header">
          <div class="header-icon">
            <el-image style="width: 32px; height: 32px" :src="url1" />
          </div>
          <div class="header-text">
            <p class="title">上传结果文件</p>
          </div>
        </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-content">
              <div class="upload-main">
                <el-button class="upload-btn">选择文件</el-button>
                <div class="file-info">
                  <div class="file-name" v-if="fileList.length">
                    {{ fileList[0].name }}
                  </div>
                  <div class="upload-tip" v-else>
                    TXT文件，大小需小于 50KB
                  </div>
                </div>
              </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
  );
};

function clearFiles() {
  fileList.value = [];
  fileContent.value = "";
  console.log("✅ 文件列表已直接清空");
}

defineExpose({
  clearFiles,
});
</script>

<style scoped lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  
  .upload-card {
    width: 450px;
    background: linear-gradient(135deg, #d2dbf1 0%, #d2dbf1 100%);
    border: 1px solid #e1e8ff;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(98, 102, 241, 0.08);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 30px rgba(98, 102, 241, 0.12);
      transform: translateY(-2px);
    }

    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .header-icon {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        box-shadow: 0 4px 12px rgba(98, 102, 241, 0.3);
      }

      .header-text {
        .title {
          font-size: 20px;
          font-weight: 700;
          color: #1a1a1a;
          margin: 0;
          background: linear-gradient(135deg, #6266f1 0%, #4f52d1 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }
    }

    .upload-area {
      .upload-content {
        .upload-main {
          display: flex;
          align-items: center;
          gap: 16px;
          background: white;
          padding: 16px;
          border: 1px solid #e8edff;
          border-radius: 12px;
          transition: all 0.3s ease;

          &:hover {
            border-color: #6266f1;
            box-shadow: 0 2px 12px rgba(98, 102, 241, 0.1);
          }

          .upload-btn {
            background: linear-gradient(135deg, #6266f1 0%, #4f52d1 100%);
            border: none;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            padding: 10px 20px;
            transition: all 0.3s ease;
            white-space: nowrap;

            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(98, 102, 241, 0.3);
            }

            &:active {
              transform: translateY(0);
            }
          }

          .file-info {
            flex: 1;
            min-width: 0;

            .file-name {
              font-size: 14px;
              font-weight: 600;
              color: #1a1a1a;
              margin: 0;
              padding: 8px 12px;
              background: #f8f9ff;
              border-radius: 6px;
              border: 1px solid #e8edff;
              word-break: break-all;
            }

            .upload-tip {
              font-size: 14px;
              color: #666;
              margin: 0;
              padding: 8px 12px;
              font-style: italic;
            }
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .container .upload-card {
    width: 100%;
    margin: 0 16px;
    padding: 20px;
    
    .upload-content .upload-main {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;
      
      .upload-btn {
        align-self: flex-start;
      }
    }
  }
}
</style>