<template>
  <view>
    <!-- 触发按钮 -->
    <slot name="trigger" :uploading="uploading">
      <button 
        :disabled="uploading"
        @click="choosePdf"
        class="upload-btn"
      >
        {{ uploading ? '上传中...' : '上传PDF' }}
      </button>
    </slot>
  </view>
</template>

<script>
export default {
  name: 'PdfUploader',
  props: {
    // 上传接口地址
    uploadUrl: {
      type: String,
      required: true
    },
    // 最大文件大小（单位：MB）
    maxSize: {
      type: Number,
      default: 50
    }
  },
  data() {
    return {
      uploading: false
    }
  },
  methods: {
    // 选择PDF文件
    async choosePdf() {
      if (this.uploading) return
      
      try {
        const [file] = await this.selectFile()
        await this.verifyFile(file)
        const result = await this.uploadFile(file)
        this.$emit('success', result)
      } catch (error) {
        this.$emit('error', error)
        this.showToast(error.message)
      }
    },

    // 选择文件
    selectFile() {
      return new Promise((resolve, reject) => {
        uni.chooseFile({
          count: 1,
          type: 'file',
          extension: ['pdf'],
          success: res => resolve(res.tempFiles),
          fail: () => reject(new Error('取消选择'))
        })
      })
    },

    // 验证文件
    verifyFile(file) {
      const maxBytes = this.maxSize * 1024 * 1024
      
      if (!file.type.includes('pdf')) {
        throw new Error('请选择PDF文件')
      }
      
      if (file.size > maxBytes) {
        throw new Error(`文件大小不能超过${this.maxSize}MB`)
      }
      
      return true
    },

    // 执行上传
    uploadFile(file) {
      this.uploading = true
      
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.uploadUrl,
          filePath: file.path,
          name: 'file',
          formData: {
            filename: file.name
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(JSON.parse(res.data))
            } else {
              reject(new Error('上传失败'))
            }
          },
          fail: () => reject(new Error('网络错误')),
          complete: () => (this.uploading = false)
        })
      })
    },

    // 显示提示
    showToast(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      })
    }
  }
}
</script>

<style scoped>
.upload-btn {
  background-color: #007AFF;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
}

.upload-btn[disabled] {
  background-color: #cccccc;
}
</style>
<!--  <SimplePdfUploader
      upload-url="https://your-api.com/upload"
      :max-size="30"
      @success="handleSuccess"
      @error="handleError"
    >
      <!-- 自定义触发按钮 -->
      <template v-slot:trigger="{ uploading }">
        <button 
          :disabled="uploading"
          class="custom-btn"
        >
          {{ uploading ? '正在上传...' : '选择PDF文件' }}
        </button>
      </template>
    </SimplePdfUploader> -->