<template>
  <div>
    <div class="container">
      <div class="up-box box2">
        <div class="up-box-top">
          <span>
            <el-image style="width: 26px; height: 26px" :src="url2" />
          </span>
          <p>上传回波影像</p>
        </div>
        <div class="upload-area">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action=""
            multiple
            :limit="1"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".json"
          >
            <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>
                JSON文件，大小需小于 500KB
              </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 up2 from '@/assets/img/up2.png'
import Encoding from 'encoding-japanese'

const url2 = up2
const fileList = ref<UploadUserFile[]>([])

// ⚡ emit 给父组件
const emit = defineEmits<{
  (e: 'json-content', data: { STFTData?: { Xdata: number; Ydata: number; Val: number }[] }): void
}>()

// 上传文件变化处理
const handleFileChange: UploadProps['onChange'] = (file, files) => {
  const selectedFile = file.raw as File
  if (!selectedFile) return

  // 文件大小限制为 120MB
  if (selectedFile.size > 120 * 1024 * 1024) {
    ElMessage.error('文件大小超过120MB，请重新选择')
    fileList.value = []
    return
  }

  // ✅ 忽略扩展名大小写判断
  if (!selectedFile.name.toLowerCase().endsWith('.json')) {
    ElMessage.error('仅支持上传JSON文件（后缀需为 .json）')
    fileList.value = []
    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' })
    }

    try {
      const jsonData = JSON.parse(content)
      console.log('✅ JSON解析成功:', jsonData)
      ElMessage.success('文件解析成功')

      const STFTData = Array.isArray(jsonData.STFTData) ? jsonData.STFTData : undefined

      if (!STFTData) {
        ElMessage.warning('JSON 文件中没有 STFTData 数组')
      } else {
        emit('json-content', { STFTData })
      }
    } catch (err) {
      console.error('❌ JSON解析失败', err)
      ElMessage.error('JSON 文件格式有误，请检查内容')
    }
  }

  reader.readAsArrayBuffer(selectedFile)
}


// 删除、预览、超出限制处理
const handleRemove: UploadProps['onRemove'] = () => {}
const handlePreview: UploadProps['onPreview'] = () => {}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`最多上传 1 个文件，当前已选 ${uploadFiles.length} 个`)
}
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
  return ElMessageBox.confirm(`确定删除 ${uploadFile.name} 吗？`).then(
    () => true,
    () => false
  )
}
</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;
      }
    }
  }

  .box2 {
    background: #fefce8;
    border: 1px solid #fde68a;

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

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

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