<template>
  <view class="download-btn" @click="handleDownload">
    <slot>
      <view class="default-btn" :class="{ downloading: downloading }">
        <text class="icon">{{ downloading ? '⏳' : '⬇️' }}</text>
        <text class="text">{{ downloading ? `下载中 ${progress}%` : '下载音频' }}</text>
        <view v-if="downloading" class="progress-bar">
          <view class="progress-fill" :style="{ width: progress + '%' }"></view>
        </view>
      </view>
    </slot>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';

interface Props {
  url: string;
  filename?: string;
  audioId?: string;
}

const props = withDefaults(defineProps<Props>(), {
  filename: 'audio.mp3',
  audioId: '',
});

const downloading = ref(false);
const progress = ref(0);
const retryCount = ref(0);
const maxRetries = 2;

async function handleDownload() {
  if (downloading.value) return;
  
  try {
    downloading.value = true;
    progress.value = 0;
    retryCount.value = 0;
    
    await downloadWithRetry();
  } catch (error) {
    console.error('[Download] 下载失败:', error);
  }
}

async function downloadWithRetry() {
  while (retryCount.value <= maxRetries) {
    try {
      await executeDownload();
      return; // 下载成功，退出重试循环
    } catch (error) {
      retryCount.value++;
      if (retryCount.value > maxRetries) {
        uni.hideLoading();
        downloading.value = false;
        uni.showModal({
          title: '下载失败',
          content: `下载失败，已重试${maxRetries}次。请检查网络连接后重试。`,
          showCancel: false,
        });
        throw error;
      }
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * retryCount.value));
    }
  }
}

async function executeDownload() {
  return new Promise<void>((resolve, reject) => {
    uni.showLoading({
      title: '下载中...',
      mask: true,
    });
    
    // 下载文件
    const downloadTask = uni.downloadFile({
      url: props.url,
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存到本地
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              uni.hideLoading();
              downloading.value = false;
              progress.value = 100;
              
              uni.showToast({
                title: '下载成功',
                icon: 'success',
                duration: 2000,
              });
              
              resolve();
            },
            fail: (err) => {
              uni.hideLoading();
              downloading.value = false;
              uni.showToast({
                title: '保存失败',
                icon: 'none',
              });
              reject(err);
            },
          });
        } else {
          reject(new Error(`下载失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        uni.hideLoading();
        downloading.value = false;
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        });
        reject(err);
      },
    });
    
    // 监听下载进度
    downloadTask.onProgressUpdate((res) => {
      progress.value = res.progress;
    });
  });
}
</script>

<style scoped>
.download-btn {
  padding: 20rpx;
}

.default-btn {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 24rpx 48rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  overflow: hidden;
  transition: opacity 0.3s;
}

.default-btn.downloading {
  opacity: 0.8;
}

.icon {
  font-size: 36rpx;
}

.text {
  font-weight: 500;
}

.progress-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 6rpx;
  background: rgba(255, 255, 255, 0.3);
}

.progress-fill {
  height: 100%;
  background: white;
  transition: width 0.3s;
}
</style>
