<template>
  <div class="container">
    <div class="upload-card box3">
      <div class="card-header">
        <div class="header-icon">
          <el-image style="width: 32px; height: 32px" :src="url3" />
        </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"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
          :auto-upload="false"
          :on-change="handleFileChange"
          accept=".json"
        >
          <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>
                  Json文件，大小需小于 500KB
                </div>
              </div>
            </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;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  
  .upload-card {
    width: 450px;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(34, 197, 94, 0.08);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 30px rgba(34, 197, 94, 0.12);
      transform: translateY(-2px);
    }

    &.box3 {
      background: linear-gradient(135deg, #d8f7e3 0%, #d8f7e3 100%);
      border: 1px solid #bbf7d0;

      .card-header {
        .header-icon {
          background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
          box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
        }

        .header-text .title {
          background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }

      .upload-content .upload-main {
        border: 1px solid #d1fae5;
        
        &:hover {
          border-color: #22c55e;
          box-shadow: 0 2px 12px rgba(34, 197, 94, 0.1);
        }

        .upload-btn {
          background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
          
          &:hover {
            box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
          }
        }

        .file-info .file-name {
          background: #f0fdf4;
          border: 1px solid #d1fae5;
        }
      }
    }

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

      .header-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
      }

      .header-text {
        .title {
          font-size: 20px;
          font-weight: 700;
          color: #1a1a1a;
          margin: 0;
        }
      }
    }

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

          .upload-btn {
            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);
            }

            &: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;
              border-radius: 6px;
              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>