const app = getApp()

Page({
  data: {
    projects: [],
    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
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.fetchData();
  },
  fetchData() {
    const { request } = require('../../utils/request')

    request({ url: '/projects' })
      .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 周'
            }
          ]
        })
      })

    request({ url: '/categories' })
      .then((data) => {
        const list = Array.isArray(data) ? data : data
        this.setData({ categories: list })
      })
      .catch(() => {
        this.setData({
          categories: [
            { name: '全部', color: 'bg-blue-100 text-blue-600' },
            { name: '编程', color: 'bg-orange-100 text-orange-600' },
            { name: '设计', color: 'bg-purple-100 text-purple-600' }
          ]
        })
      })
  },
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    })
  }
})
