const app = getApp()

Page({
  data: {
    projects: [],
    banners: [],
    categories: [],
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    selectedCategory: 'all',
    showcases: [],
    categoryStats: {},
    unreadCount: 0
  },
  onShow() {
      this.fetchUnreadCount();
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.fetchData();
    this.fetchBanners();
    this.fetchShowcases();
    this.fetchCategoryStats();
  },
  handleCategorySelect(e) {
      const type = e.currentTarget.dataset.type;
      this.setData({ selectedCategory: type });
      this.fetchData(type);
  },
  fetchUnreadCount() {
    // Only fetch if logged in
    const app = getApp()
    if (!app.globalData.token) return;

    console.log('Fetching unread count...');
    const { request } = require('../../utils/request')
    request({ url: '/notifications/unread_count/' })
      .then(res => {
        if (res && typeof res.count === 'number') {
          this.setData({ unreadCount: res.count })
        }
      })
      .catch(err => console.error('Fetch unread count error:', err))
  },
  handleNotificationClick() {
    wx.navigateTo({
      url: '/pages/message/index'
    })
  },
  fetchBanners() {
    const { request } = require('../../utils/request')
    request({ url: '/banners/?is_active=true' })
      .then(data => {
        const list = Array.isArray(data) ? data : (data && data.results) || []
        this.setData({ banners: list })
      })
      .catch(err => console.error('Fetch banners error:', err))
  },
  handleBannerClick(e) {
      const item = e.currentTarget.dataset.item;
      if (item.project) {
          wx.navigateTo({
              url: `/pages/detail/detail?id=${item.project}`
          })
      } else if (item.link) {
          // Simple link handling (copy or webview)
          // For simplicity, if it starts with http, copy it
          if (item.link.startsWith('http')) {
              wx.setClipboardData({
                  data: item.link,
                  success: () => wx.showToast({ title: '链接已复制', icon: 'none' })
              })
          }
      }
  },
  fetchShowcases() {
    const { request } = require('../../utils/request')
    request({ url: '/student-showcases/?is_active=true' })
      .then(data => {
        const list = Array.isArray(data) ? data : (data && data.results) || []
        this.setData({ showcases: list })
      })
      .catch(err => console.error('Fetch showcases error:', err))
  },
  playVideo(e) {
      let url = e.currentTarget.dataset.url;
      if (!url) return;

      // Fix for local development: replace localhost/127.0.0.1 with actual API host
      if (url.includes('localhost') || url.includes('127.0.0.1')) {
          const app = getApp();
          // Extract host from baseUrl (e.g. http://127.0.0.1:8000/api -> http://127.0.0.1:8000)
          const apiBase = app.globalData.baseUrl.split('/api')[0];
          // Replace the localhost part
          url = url.replace(/http:\/\/localhost:\d+/, apiBase)
                   .replace(/http:\/\/127.0.0.1:\d+/, apiBase);
      }
      
      // Use previewMedia for all video urls as our backend uploads files directly now
      wx.previewMedia({
          sources: [{ url: url, type: 'video' }],
          success: () => console.log('Preview success'),
          fail: (err) => {
              console.error('Preview failed', err);
              // Fallback for non-previewable links
              wx.setClipboardData({
                  data: url,
                  success: () => wx.showToast({ title: '视频链接已复制', icon: 'none' })
              })
          }
      })
  },
  fetchData(type = 'all') {
    const { request } = require('../../utils/request')
    let url = '/projects/';
    if (type !== 'all') {
        url += `?project_type=${type}`;
    }

    request({ url: url })
      .then((data) => {
        const list = Array.isArray(data) ? data : (data && data.results) || []
        this.setData({ projects: list })
      })
      .catch((err) => {
        console.error(err)
        this.setData({
          projects: [
            {
              id: 1,
              title: 'Python 数据分析实战',
              category: '编程开发',
              image:
                'https://images.unsplash.com/photo-1526379095098-d400fd0bf935?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3',
              students: 1205,
              rating: 4.8,
              duration: '12 周'
            },
            {
              id: 2,
              title: '零基础英语口语速成',
              category: '语言学习',
              image:
                'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3',
              students: 850,
              rating: 4.9,
              duration: '8 周'
            }
          ]
        })
      })
  },
  fetchCategoryStats() {
    const { request } = require('../../utils/request')
    request({ url: '/dashboard/stats' })
      .then(res => {
          const stats = {};
          if (res.pie_chart_data) {
              res.pie_chart_data.forEach(item => {
                  if (item.type) {
                      stats[item.type] = item.value;
                  }
              });
          }
          this.setData({ categoryStats: stats });
      })
      .catch(err => console.error('Fetch stats error:', err))
  },
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    })
  }
})
