import { createSSRApp } from 'vue'
import App from './App.vue'

export function createApp() {
  const app = createSSRApp(App)
  
  // 全局配置
  app.config.globalProperties.$baseUrl = 'https://api.farming.com'
  
  // 全局方法
  app.config.globalProperties.$request = (options) => {
    return new Promise((resolve, reject) => {
      // 添加token
      const token = uni.getStorageSync('token')
      if (token) {
        options.header = options.header || {}
        options.header.Authorization = 'Bearer ' + token
      }
      
      // 添加基础URL
      if (!options.url.startsWith('http')) {
        options.url = app.config.globalProperties.$baseUrl + options.url
      }
      
      // 发起请求
      uni.request({
        ...options,
        success: (res) => {
          if (res.data.code === 200) {
            resolve(res.data)
          } else if (res.data.code === 401) {
            // token过期，跳转登录
            uni.removeStorageSync('token')
            uni.navigateTo({
              url: '/pages/auth/login'
            })
            reject(res.data)
          } else {
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        },
        fail: (error) => {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  }
  
  // 全局工具方法
  app.config.globalProperties.$utils = {
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 格式化日期
    formatDate(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 格式化金额
    formatMoney(amount) {
      return '¥' + Number(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
    },
    
    // 防抖
    debounce(func, wait) {
      let timeout
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout)
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    },
    
    // 节流
    throttle(func, limit) {
      let inThrottle
      return function() {
        const args = arguments
        const context = this
        if (!inThrottle) {
          func.apply(context, args)
          inThrottle = true
          setTimeout(() => inThrottle = false, limit)
        }
      }
    }
  }
  
  return {
    app
  }
}