/**
 * 省胜优铺 API 封装模块（三端对齐版）
 * 统一请求处理：baseUrl、token注入、错误处理、loading状态
 * 对齐后端路由契约（/api/product /api/order /api/marketing /api/user ...）
 */
const app = getApp();
let token = '';

// 设置token
function setToken(t) {
  token = t;
  if (t) {
    wx.setStorageSync('token', t);
  } else {
    wx.removeStorageSync('token');
  }
}

// 获取token
function getToken() {
  if (!token) {
    token = wx.getStorageSync('token') || '';
  }
  return token;
}

/**
 * 通用请求方法
 * @param {string} method - 请求方法
 * @param {string} path - API路径（如 '/api/product/list'）
 * @param {object} data - 请求体/参数
 * @param {object} options - 配置项
 * @param {boolean} options.showLoading - 是否显示loading
 * @param {boolean} options.noAuth - 无需登录
 * @param {string} options.loadingText - loading文字
 * @returns {Promise}
 */
function request(method, path, data = {}, options = {}) {
  const { showLoading = false, noAuth = false, loadingText = '加载中...' } = options;
  const baseUrl = app.globalData.baseUrl || 'https://ssypco.com';

  return new Promise((resolve, reject) => {
    // 显示loading
    if (showLoading) {
      wx.showLoading({ title: loadingText, mask: true });
    }

    // 构建请求头
    const header = { 'Content-Type': 'application/json' };
    const t = getToken();
    if (t && !noAuth) {
      header['Authorization'] = 'Bearer ' + t;
    }

    // GET请求将data放到params
    const isGet = method === 'GET';
    const requestData = isGet ? {} : data;

    wx.request({
      url: baseUrl + path,
      method,
      data: isGet ? data : requestData,
      header,
      timeout: 15000,
      success(res) {
        if (showLoading) wx.hideLoading();

        const body = res.data;

        // 后端统一返回 { code, message, data }
        if (body && (body.code === 0 || body.code === undefined)) {
          resolve(body.data !== undefined ? body.data : body);
        } else if (body && body.code === 401) {
          // token过期，清除登录态，跳转登录
          setToken('');
          wx.removeStorageSync('userInfo');
          wx.showToast({ title: '登录已过期', icon: 'none' });
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/login/login' });
          }, 1500);
          reject(new Error(body.message || '登录已过期'));
        } else {
          // 业务错误
          wx.showToast({ title: (body && body.message) || '请求失败', icon: 'none' });
          reject(new Error((body && body.message) || '请求失败'));
        }
      },
      fail(err) {
        if (showLoading) wx.hideLoading();
        wx.showToast({ title: '网络连接失败', icon: 'none' });
        reject(err);
      }
    });
  });
}

// ========== 便捷方法 ==========
const api = {
  setToken,
  getToken,
  get: (path, data, opts) => request('GET', path, data, opts),
  post: (path, data, opts) => request('POST', path, data, opts),
  put: (path, data, opts) => request('PUT', path, data, opts),
  delete: (path, data, opts) => request('DELETE', path, data, opts),

  // ========== 首页 ==========
  getBanners: () => request('GET', '/api/banner/list'),
  getRecommendProducts: () => request('GET', '/api/product/recommend'),
  getNewProducts: () => request('GET', '/api/product/new'),
  getHotProducts: () => request('GET', '/api/product/hot'),
  getProductList: (params) => request('GET', '/api/product/list', params),

  // ========== 分类 ==========
  getCategories: () => request('GET', '/api/category/list'),
  getCategoryProducts: (id, params) => request('GET', `/api/product/category/${id}`, params),

  // ========== 商品 ==========
  getProductDetail: (id) => request('GET', `/api/product/detail/${id}`),
  getProductReviews: (id, params) => request('GET', `/api/review/list/${id}`, params),

  // ========== 用户 ==========
  login: (data) => request('POST', '/api/user/login', data, { noAuth: true }),
  register: (data) => request('POST', '/api/user/register', data, { noAuth: true }),
  wxLogin: (data) => request('POST', '/api/user/wx-login', data, { noAuth: true }),
  smsLogin: (data) => request('POST', '/api/user/sms-login', data, { noAuth: true }),
  getUserInfo: () => request('GET', '/api/user/info'),
  updateUserInfo: (data) => request('PUT', '/api/user/info', data),
  changePassword: (data) => request('PUT', '/api/user/password', data),
  getUserLevel: () => request('GET', '/api/user/level'),
  getUserStats: () => request('GET', '/api/user/stats'),
  getPoints: () => request('GET', '/api/user/points'),
  getPointsLogs: (params) => request('GET', '/api/user/points/logs', params),
  getNotifications: () => request('GET', '/api/user/notifications'),
  readNotifications: () => request('PUT', '/api/user/notifications/read'),
  getBrowseHistory: (params) => request('GET', '/api/user/browse-history', params),
  addBrowseHistory: (productId) => request('POST', '/api/user/browse-history', { product_id: productId }),

  // ========== 地址 ==========
  getAddressList: () => request('GET', '/api/user/address'),
  saveAddress: (data) => request('POST', '/api/user/address', data),
  updateAddress: (id, data) => request('PUT', `/api/user/address/${id}`, data),
  deleteAddress: (id) => request('DELETE', `/api/user/address/${id}`),
  setDefaultAddress: (id) => request('PUT', `/api/user/address/${id}/default`),

  // ========== 购物车 ==========
  getCartList: () => request('GET', '/api/cart/list'),
  addCart: (data) => request('POST', '/api/cart/add', data),
  updateCart: (id, data) => request('PUT', `/api/cart/${id}`, data),
  deleteCart: (id) => request('DELETE', `/api/cart/${id}`),
  clearCart: () => request('DELETE', '/api/cart'),
  toggleCartSelect: (data) => request('POST', '/api/cart/toggle-select', data),
  selectAllCart: (data) => request('POST', '/api/cart/select-all', data),

  // ========== 订单 ==========
  getOrderList: (params) => request('GET', '/api/order/list', params),
  getOrderDetail: (orderNo) => request('GET', `/api/order/detail/${orderNo}`),
  createOrder: (data) => request('POST', '/api/order/create', data),
  calcAmount: (data) => request('POST', '/api/order/calc-amount', data),
  cancelOrder: (orderNo, data) => request('POST', `/api/order/${orderNo}/cancel`, data),
  confirmOrder: (orderNo) => request('POST', `/api/order/${orderNo}/confirm`),
  payOrder: (orderNo, data) => request('POST', `/api/order/${orderNo}/pay`, data),
  miniappPay: (data) => request('POST', '/api/miniapp-pay/order', data),
  applyRefund: (data) => request('POST', '/api/aftersale/apply', data),
  getRefundList: (params) => request('GET', '/api/aftersale/my', params),
  cancelRefund: (id) => request('POST', `/api/aftersale/${id}/cancel`),
  submitReturnRefund: (id, data) => request('POST', `/api/aftersale/${id}/return`, data),
  getShippingCompanies: () => request('GET', '/api/order/shipping-companies'),

  // ========== 支付 ==========
  createPayment: (data) => request('POST', '/api/payment/create', data),
  getPaymentStatus: (orderNo) => request('GET', `/api/payment/status/${orderNo}`),
  getPaymentCapabilities: () => request('GET', '/api/payment/capabilities'),

  // ========== 评价 ==========
  createReview: (data) => request('POST', '/api/review/create', data),
  followUpReview: (data) => request('POST', '/api/review/follow-up', data),
  toggleReviewLike: (data) => request('POST', '/api/review/like', data),
  replyReview: (data) => request('POST', '/api/review/reply', data),
  getMyReviews: (params) => request('GET', '/api/review/my', params),

  // ========== 收藏 ==========
  getFavorites: (params) => request('GET', '/api/user/favorites', params),
  addFavorite: (productId) => request('POST', '/api/user/favorite', { product_id: productId }),
  removeFavorite: (productId) => request('DELETE', `/api/user/favorite/${productId}`),

  // ========== 营销（优惠券/秒杀/拼团/签到） ==========
  getCoupons: () => request('GET', '/api/marketing/coupons', {}, { noAuth: true }),
  receiveCoupon: (couponId) => request('POST', '/api/marketing/coupon/receive', { coupon_id: couponId }),
  getMyCoupons: (params) => request('GET', '/api/marketing/coupon/user', params),
  getSeckillList: () => request('GET', '/api/marketing/seckill/list', {}, { noAuth: true }),
  getSeckillDetail: (id) => request('GET', `/api/marketing/seckill/${id}`, {}, { noAuth: true }),
  buySeckill: (seckillId) => request('POST', '/api/marketing/seckill/buy', { seckill_id: seckillId }),
  getGroupBuyList: () => request('GET', '/api/marketing/group-buy/list', {}, { noAuth: true }),
  getGroupBuyDetail: (id) => request('GET', `/api/marketing/group-buy/${id}`, {}, { noAuth: true }),
  // ========== 预售 ==========
  getPresaleList: () => request('GET', '/api/presale/list', {}, { noAuth: true }),
  getPresaleDetail: (id) => request('GET', `/api/presale/${id}`, {}, { noAuth: true }),
  createPresaleOrder: (data) => request('POST', '/api/presale/order', data),
  payFinalAmount: (orderNo) => request('POST', `/api/presale/order/${orderNo}/pay-final`, {}),
  getPresaleOrders: (params) => request('GET', '/api/presale/orders', params),
  // ========== 砍价 ==========
  getBargainList: (params) => request('GET', '/api/bargain/list', params, { noAuth: true }),
  getBargainDetail: (id) => request('GET', `/api/bargain/${id}`, {}, { noAuth: true }),
  startBargain: (data) => request('POST', '/api/bargain/start', data),
  helpBargain: (data) => request('POST', '/api/bargain/help', data),
  getBargainSessionDetail: (no) => request('GET', `/api/bargain/session/${no}`, {}, { noAuth: true }),
  getBargainSessions: (params) => request('GET', '/api/bargain/session', params),
  bargainOrder: (data) => request('POST', '/api/bargain/order', data),
  getPromotions: () => request('GET', '/api/marketing/promotions', {}, { noAuth: true }),
  calcPromotion: (data) => request('POST', '/api/marketing/promotions/calc', data),
  // 促销中心聚合(秒杀/拼团/砍价/预售/领券)
  getPromotionCenter: () => request('GET', '/api/marketing/promotion-center', {}, { noAuth: true }),
  getCheckinStatus: () => request('GET', '/api/marketing/checkin/status'),
  doCheckin: () => request('POST', '/api/marketing/checkin'),

  // ========== 会员(VIP) ==========
  getMembershipPlans: () => request('GET', '/api/membership/plans', {}, { noAuth: true }),
  buyMembership: (data) => request('POST', '/api/membership/buy', data),
  getMyMembership: () => request('GET', '/api/membership/my'),
  getMembershipHistory: () => request('GET', '/api/membership/history'),

  // ========== 分销 ==========
  getDistributionInfo: () => request('GET', '/api/distribution/info'),
  getDistributionTeam: (params) => request('GET', '/api/distribution/team', params),
  getCommissionRecords: (params) => request('GET', '/api/distribution/commission', params),
  getCommissionStat: () => request('GET', '/api/distribution/commission/stat'),
  getDistributionLevels: () => request('GET', '/api/distribution/level'),
  applyWithdraw: (data) => request('POST', '/api/distribution/withdraw', data),
  getWithdrawList: (params) => request('GET', '/api/distribution/withdraw/list', params),
  getDistributionQrcode: () => request('GET', '/api/distribution/qrcode'),
  bindParent: (parentId) => request('POST', '/api/distribution/bind', { parent_id: parentId }),
  getDistributionStatus: () => request('GET', '/api/distribution/status'),
  applyDistribution: (data) => request('POST', '/api/distribution/apply', data),

  // ========== 积分兑换 ==========
  getExchangeProducts: (params) => request('GET', '/api/exchange/products', params, { noAuth: true }),
  getExchangeProduct: (id) => request('GET', `/api/exchange/products/${id}`, {}, { noAuth: true }),
  createExchangeOrder: (data) => request('POST', '/api/exchange/order', data),
  getExchangeOrders: (params) => request('GET', '/api/exchange/orders', params),
  getExchangeOrder: (id) => request('GET', `/api/exchange/orders/${id}`),
  cancelExchangeOrder: (id) => request('POST', `/api/exchange/orders/${id}/cancel`, {}),

  // ========== 充值 ==========
  getRechargePlans: () => request('GET', '/api/recharge/plans', {}, { noAuth: true }),
  getBalance: () => request('GET', '/api/recharge/balance'),
  createRechargeOrder: (data) => request('POST', '/api/recharge/order', data),
  getRechargeOrders: (params) => request('GET', '/api/recharge/orders', params),

  // ========== 装修渲染(v1.4.3) ==========
  // 获取指定终端+页面的装修模板; 授权后返回components, free返回enabled:false
  getDecor: (terminal, page) => request('GET', `/design/render/${terminal}`, { page }, { noAuth: true }),

  // ========== 系统 ==========
};

module.exports = api;
