/**
 * TabBar 图标下载脚本
 * 从 Iconfont 下载图标并自动配置
 */

const https = require('https');
const fs = require('fs');
const path = require('path');

// 图标配置
const icons = [
  {
    name: 'home',
    url: 'https://img.icons8.com/ios/100/999999/home--v1.png',
    desc: '首页-未选中'
  },
  {
    name: 'home-active',
    url: 'https://img.icons8.com/ios-filled/100/07c160/home--v1.png',
    desc: '首页-选中'
  },
  {
    name: 'article',
    url: 'https://img.icons8.com/ios/100/999999/document--v1.png',
    desc: '我的发布-未选中'
  },
  {
    name: 'article-active',
    url: 'https://img.icons8.com/ios-filled/100/07c160/document--v1.png',
    desc: '我的发布-选中'
  },
  {
    name: 'user',
    url: 'https://img.icons8.com/ios/100/999999/user--v1.png',
    desc: '我的-未选中'
  },
  {
    name: 'user-active',
    url: 'https://img.icons8.com/ios-filled/100/07c160/user--v1.png',
    desc: '我的-选中'
  }
];

// 创建目标目录
const targetDir = path.join(__dirname, 'miniprogram', 'images', 'tabbar');
if (!fs.existsSync(targetDir)) {
  fs.mkdirSync(targetDir, { recursive: true });
  console.log('✅ 创建目录:', targetDir);
}

// 下载单个图标
function downloadIcon(icon) {
  return new Promise((resolve, reject) => {
    const filePath = path.join(targetDir, `${icon.name}.png`);
    const file = fs.createWriteStream(filePath);

    https.get(icon.url, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close();
        console.log(`✅ 下载成功: ${icon.desc} (${icon.name}.png)`);
        resolve();
      });
    }).on('error', (err) => {
      fs.unlink(filePath, () => {});
      console.error(`❌ 下载失败: ${icon.desc}`, err.message);
      reject(err);
    });
  });
}

// 批量下载
async function downloadAll() {
  console.log('\n🚀 开始下载 TabBar 图标...\n');
  
  try {
    for (const icon of icons) {
      await downloadIcon(icon);
      // 延迟避免请求过快
      await new Promise(resolve => setTimeout(resolve, 500));
    }
    
    console.log('\n✨ 所有图标下载完成！\n');
    console.log('📁 图标位置:', targetDir);
    console.log('\n📝 下一步：');
    console.log('1. 打开 miniprogram/app.json');
    console.log('2. 在 tabBar.list 中添加图标路径');
    console.log('3. 重新编译小程序\n');
    
  } catch (error) {
    console.error('\n❌ 下载过程出错:', error);
  }
}

// 执行下载
downloadAll();
