// 牛肉商城小程序
App({
  globalData: {
    userInfo: null,
    token: null,
    apiBase: 'https://api.xlxumu.com',
    version: '1.0.0',
    cart: [],
    cartCount: 0
  },

  onLaunch() {
    console.log('牛肉商城小程序启动');
    
    // 检查更新
    this.checkForUpdate();
    
    // 初始化用户信息
    this.initUserInfo();
    
    // 初始化购物车
    this.initCart();
    
    // 设置网络状态监听
    this.setupNetworkListener();
  },

  onShow() {
    console.log('牛肉商城小程序显示');
  },

  onHide() {
    console.log('牛肉商城小程序隐藏');
  },

  onError(msg) {
    console.error('小程序错误：', msg);
  },

  // 检查小程序更新
  checkForUpdate() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      
      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          console.log('发现新版本');
        }
      });
      
      updateManager.onUpdateReady(() => {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: (res) => {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          }
        });
      });
      
      updateManager.onUpdateFailed(() => {
        console.error('新版本下载失败');
      });
    }
  },

  // 初始化用户信息
  initUserInfo() {
    try {
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      
      if (token && userInfo) {
        this.globalData.token = token;
        this.globalData.userInfo = userInfo;
      }
    } catch (error) {
      console.error('初始化用户信息失败：', error);
    }
  },

  // 初始化购物车
  initCart() {
    try {
      const cart = wx.getStorageSync('cart') || [];
      this.globalData.cart = cart;
      this.updateCartCount();
    } catch (error) {
      console.error('初始化购物车失败：', error);
    }
  },

  // 设置网络状态监听
  setupNetworkListener() {
    wx.onNetworkStatusChange((res) => {
      if (!res.isConnected) {
        this.showError('网络连接已断开');
      }
    });
  },

  // 微信登录
  async wxLogin() {
    try {
      // 检查登录状态
      const loginRes = await this.checkSession();
      if (loginRes) {
        return this.globalData.userInfo;
      }
    } catch (error) {
      console.log('登录状态已过期，重新登录');
    }

    try {
      // 获取登录code
      const { code } = await this.promisify(wx.login)();
      
      // 获取用户信息
      const userProfile = await this.getUserProfile();
      
      // 发送登录请求
      const response = await this.request({
        url: '/auth/wechat/login',
        method: 'POST',
        data: {
          code,
          encrypted_data: userProfile.encryptedData,
          iv: userProfile.iv
        }
      });
      
      const { token, user } = response.data;
      
      // 保存用户信息
      this.globalData.token = token;
      this.globalData.userInfo = user;
      
      wx.setStorageSync('token', token);
      wx.setStorageSync('userInfo', user);
      
      return user;
      
    } catch (error) {
      console.error('微信登录失败：', error);
      throw error;
    }
  },

  // 检查登录状态
  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: () => {
          if (this.globalData.userInfo) {
            resolve(this.globalData.userInfo);
          } else {
            reject(new Error('用户信息不存在'));
          }
        },
        fail: reject
      });
    });
  },

  // 获取用户信息
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: resolve,
        fail: reject
      });
    });
  },

  // 网络请求封装
  async request(options) {
    const {
      url,
      method = 'GET',
      data = {},
      header = {}
    } = options;

    // 添加认证头
    if (this.globalData.token) {
      header.Authorization = `Bearer ${this.globalData.token}`;
    }

    try {
      const response = await this.promisify(wx.request)({
        url: this.globalData.apiBase + url,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          ...header
        }
      });

      const { statusCode, data: responseData } = response;

      if (statusCode === 200) {
        if (responseData.code === 0) {
          return responseData;
        } else {
          throw new Error(responseData.message || '请求失败');
        }
      } else if (statusCode === 401) {
        // 登录过期，清除用户信息
        this.clearUserInfo();
        wx.navigateTo({
          url: '/pages/auth/login'
        });
        throw new Error('登录已过期，请重新登录');
      } else {
        throw new Error(`请求失败：${statusCode}`);
      }
    } catch (error) {
      console.error('请求错误：', error);
      throw error;
    }
  },

  // 清除用户信息
  clearUserInfo() {
    this.globalData.token = null;
    this.globalData.userInfo = null;
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
  },

  // 购物车管理
  addToCart(product, quantity = 1, specs = {}) {
    const cartItem = {
      id: product.id,
      title: product.title,
      price: product.price,
      image: product.cover_image,
      quantity,
      specs,
      selected: true,
      addTime: Date.now()
    };

    // 检查是否已存在相同商品和规格
    const existingIndex = this.globalData.cart.findIndex(item => 
      item.id === product.id && JSON.stringify(item.specs) === JSON.stringify(specs)
    );

    if (existingIndex >= 0) {
      // 增加数量
      this.globalData.cart[existingIndex].quantity += quantity;
    } else {
      // 添加新商品
      this.globalData.cart.push(cartItem);
    }

    this.saveCart();
    this.updateCartCount();
    
    this.showSuccess('已添加到购物车');
  },

  // 从购物车移除
  removeFromCart(productId, specs = {}) {
    this.globalData.cart = this.globalData.cart.filter(item => 
      !(item.id === productId && JSON.stringify(item.specs) === JSON.stringify(specs))
    );
    
    this.saveCart();
    this.updateCartCount();
  },

  // 更新购物车商品数量
  updateCartQuantity(productId, specs, quantity) {
    const item = this.globalData.cart.find(item => 
      item.id === productId && JSON.stringify(item.specs) === JSON.stringify(specs)
    );
    
    if (item) {
      if (quantity <= 0) {
        this.removeFromCart(productId, specs);
      } else {
        item.quantity = quantity;
        this.saveCart();
        this.updateCartCount();
      }
    }
  },

  // 清空购物车
  clearCart() {
    this.globalData.cart = [];
    this.saveCart();
    this.updateCartCount();
  },

  // 保存购物车到本地
  saveCart() {
    try {
      wx.setStorageSync('cart', this.globalData.cart);
    } catch (error) {
      console.error('保存购物车失败：', error);
    }
  },

  // 更新购物车数量
  updateCartCount() {
    const count = this.globalData.cart.reduce((total, item) => total + item.quantity, 0);
    this.globalData.cartCount = count;
    
    // 更新tabBar徽标
    if (count > 0) {
      wx.setTabBarBadge({
        index: 2, // 购物车tab的索引
        text: count > 99 ? '99+' : count.toString()
      });
    } else {
      wx.removeTabBarBadge({
        index: 2
      });
    }
  },

  // 计算购物车总价
  getCartTotal() {
    return this.globalData.cart
      .filter(item => item.selected)
      .reduce((total, item) => total + (item.price * item.quantity), 0);
  },

  // Promise化微信API
  promisify(fn) {
    return (options = {}) => {
      return new Promise((resolve, reject) => {
        fn({
          ...options,
          success: resolve,
          fail: reject
        });
      });
    };
  },

  // 显示加载提示
  showLoading(title = '加载中...') {
    wx.showLoading({
      title,
      mask: true
    });
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },

  // 显示成功提示
  showSuccess(title) {
    wx.showToast({
      title,
      icon: 'success',
      duration: 2000
    });
  },

  // 显示错误提示
  showError(title) {
    wx.showToast({
      title,
      icon: 'none',
      duration: 3000
    });
  },

  // 显示确认对话框
  showConfirm(options) {
    return new Promise((resolve) => {
      wx.showModal({
        title: options.title || '提示',
        content: options.content,
        confirmText: options.confirmText || '确定',
        cancelText: options.cancelText || '取消',
        success: (res) => {
          resolve(res.confirm);
        }
      });
    });
  },

  // 格式化价格
  formatPrice(price) {
    if (!price) return '¥0.00';
    return `¥${parseFloat(price).toFixed(2)}`;
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) { // 1天内
      return `${Math.floor(diff / 3600000)}小时前`;
    } else if (diff < 2592000000) { // 30天内
      return `${Math.floor(diff / 86400000)}天前`;
    } else {
      return date.toLocaleDateString();
    }
  }
});