import request from "@/utils/request";

const PAYMENT_BASE_URL = 'https://662993rq13tg.vicp.fun';
const PAYMENT_TIMEOUT = 15000;

const buildPaymentUrl = (pathOrUrl = '') => {
  const deviceInfo = uni.getStorageSync('deviceInfo') || {};
  const devId = deviceInfo.deviceId || '';
  const sbmc = deviceInfo.model || '';
  const hasProtocol = /^https?:\/\//.test(pathOrUrl);
  const baseUrl = hasProtocol ? pathOrUrl : `${PAYMENT_BASE_URL}${pathOrUrl}`;
  const separator = baseUrl.includes('?') ? '&' : '?';
  return `${baseUrl}${separator}devId=${encodeURIComponent(devId)}&sbmc=${encodeURIComponent(sbmc)}`;
};

const formatFormData = (data) => {
  if (!data || typeof data !== 'object') return data;
  return Object.keys(data)
    .map((key) => {
      const value = data[key];
      if (Array.isArray(value)) {
        return value.map((item) => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join('&');
      }
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    })
    .join('&');
};

const showPaymentLoading = (loadingOptions) => {
  if (loadingOptions === false) {
    return () => {};
  }

  const config = typeof loadingOptions === 'object' ? loadingOptions : {};
  const shouldShow = loadingOptions === undefined ? true : config.show !== false;
  if (!shouldShow) {
    return () => {};
  }

  const title = config.title || (typeof loadingOptions === 'string' ? loadingOptions : '加载中...');
  const mask = config.mask ?? true;
  const delay = config.delay ?? 300;
  const loadingManager = request.loadingManager;

  if (loadingManager) {
    loadingManager.show({ title, mask, delay });
    return () => loadingManager.hide();
  }

  uni.showLoading({ title, mask });
  return () => {
    try {
      uni.hideLoading();
    } catch (error) {
      console.warn('hideLoading failed:', error);
    }
  };
};

const paymentRequest = (pathOrUrl, {
  method = 'POST',
  data = {},
  loading,
  formData = false,
  timeout = PAYMENT_TIMEOUT,
} = {}) => {
  const hideLoading = showPaymentLoading(loading);
  const requestMethod = String(method || 'POST').toUpperCase();

  let requestData = data;
  if (formData) {
    requestData = formatFormData(data);
  }

  const headers = {};
  headers['content-type'] = formData
    ? 'application/x-www-form-urlencoded'
    : 'application/json';

  const jsessionId = uni.getStorageSync('JSESSIONID');
  if (jsessionId) {
    headers['Cookie'] = `JSESSIONID=${jsessionId}`;
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: buildPaymentUrl(pathOrUrl),
      method: requestMethod,
      data: requestData,
      timeout,
      header: headers,
      success: (res) => {
        const resHeader = res.header || {};
        const setCookie = resHeader['set-cookie'] || resHeader['Set-Cookie'];
        if (setCookie) {
          const match = setCookie.match(/JSESSIONID=([^;]+)/);
          if (match && match[1]) {
            uni.setStorageSync('JSESSIONID', match[1]);
          }
        }

        if (res.statusCode === 200) {
          resolve({ data: res.data });
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(err);
      },
      complete: () => {
        hideLoading();
      }
    });
  });
};

/**
 * 支付相关 API
 * 注意：接口地址需要根据后端实际提供的地址进行修改
 */
export const paymentApi = {
  /**
   * 创建充值订单并获取支付参数
   * @param {Object} data - 订单信息
   * @param {Number} data.amount - 充值金额（单位：元）
   * @param {String} data.studentId - 学生ID（可选）
   * @param {String} data.cardNo - 卡号（可选）
   * @returns {Promise} 返回微信支付所需参数
   */
  createRechargeOrder(_data) {
    return paymentRequest('/order/payOrder', {
      method: 'POST',
      data: undefined,
      loading: {
        title: '正在创建订单...'
      }
    });
  },

  /**
   * 查询订单状态
   * @param {String} orderId - 订单ID
   * @returns {Promise}
   */
  queryOrderStatus(outTradeNo) {
    const url = outTradeNo
      ? `/order/getOrder?outTradeNo=${encodeURIComponent(outTradeNo)}`
      : '/order/getOrder'
    return paymentRequest(url, {
      method: 'GET',
      data: undefined,
      loading: false
    });
  },

  /**
   * 获取充值记录列表
   * @param {Object} params - 查询参数
   * @returns {Promise}
   */
  getRechargeHistory(params) {
    return paymentRequest('/api/payment/recharge/history', {
      data: params,
      loading: {
        title: '加载中...'
      }
    });
  }
};
