<template>
  <div class="container">
    <div class="up-box box3">
      <div class="up-box-top">
        <span>
          <el-image style="width: 26px; height: 26px" :src="url3" />
        </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>
</template>

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

const url3 = up3
const fileList = ref<UploadUserFile[]>([])

// ⚡ emit 事件定义
const emit = defineEmits<{
  (e: 'json-content', data: { Time: number; Val: number }[]): void
}>()

// 解析 JSON 文件
const handleFileChange: UploadProps['onChange'] = (file, files) => {
  const selectedFile = file.raw as File
  if (!selectedFile) return

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

  if (!selectedFile.name.endsWith('.json')) {
    ElMessage.error('仅支持上传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('文件解析成功')

      // ✅ 改为解析 TimeDomainData 数组
      if (jsonData && Array.isArray(jsonData.TimeDomainData)) {
        emit('json-content', jsonData.TimeDomainData)
      } else {
        ElMessage.warning('JSON 文件中没有 TimeDomainData 数组')
      }
    } 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 setup> 末尾添加
function clearFiles() {
  fileList.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;
      }
    }
  }
  .analysis-btn-wrapper {
    margin-top: 76px;
  }

  /* box1 紫色主题 */
  .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;
      }
    }
  }

  /* box2 黄色主题 */
  .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;
      }
    }
  }

  /* box3 绿色主题 */
  .box3 {
    background: #ecfdf5;
    border: 1px solid #bbf7d0;

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

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

      &:hover {
        background-color: #16a34a !important;
        border-color: #16a34a !important;
      }
    }
  }
}
  /* box1 紫色主题 */
  .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>
