// 支付界面逻辑

(function() {
  let overlay = null;
  let container = null;
  let closeBtn = null;
  let cancelBtn = null;
  let itemNameEl = null;
  let itemPriceEl = null;
  
  let currentPaymentData = null;
  let resolveCallback = null;

  function init() {
    overlay = document.getElementById('payViewOverlay');
    container = document.getElementById('payViewContainer');
    closeBtn = document.getElementById('payViewClose');
    cancelBtn = document.getElementById('payCancelBtn');
    itemNameEl = document.getElementById('payItemName');
    itemPriceEl = document.getElementById('payItemPrice');

    if (!overlay || !container) {
      console.error('[PayView] 支付界面元素未找到');
      return;
    }

    bindEvents();
  }

  function bindEvents() {
    // 关闭按钮 - 点击关闭视为支付成功
    if (closeBtn) {
      closeBtn.addEventListener('click', handlePaymentSuccess);
    }

    // 取消按钮 - 点击取消视为支付成功（演示模式）
    if (cancelBtn) {
      cancelBtn.addEventListener('click', handlePaymentSuccess);
    }

    // 点击遮罩层关闭 - 视为支付成功
    if (overlay) {
      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
          handlePaymentSuccess();
        }
      });
    }

    // ESC 键关闭 - 视为支付成功
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && overlay && overlay.classList.contains('show')) {
        handlePaymentSuccess();
      }
    });

    // 监听来自父窗口的消息
    window.addEventListener('message', (event) => {
      if (event.data && event.data.type === 'open-pay-view') {
        show(event.data.itemName, event.data.price, event.data.resourcePath, event.data.categoryDir);
      }
    });
  }

  function show(itemName, price, resourcePath, categoryDir) {
    if (!overlay) {
      init();
    }

    // 保存支付数据
    currentPaymentData = {
      itemName,
      price,
      resourcePath,
      categoryDir
    };

    // 更新显示内容
    if (itemNameEl) {
      itemNameEl.textContent = itemName;
    }
    if (itemPriceEl) {
      itemPriceEl.textContent = `¥${price}`;
    }

    // 显示支付界面
    overlay.classList.add('show');
    overlay.style.pointerEvents = 'auto';

    // 返回 Promise，等待支付结果
    return new Promise((resolve) => {
      resolveCallback = resolve;
    });
  }

  function hide() {
    if (overlay) {
      overlay.classList.remove('show');
      // 确保遮罩层不会阻止点击
      overlay.style.pointerEvents = 'none';
    }
    currentPaymentData = null;
    resolveCallback = null;
  }

  async function handlePaymentSuccess() {
    if (!currentPaymentData) {
      hide();
      return;
    }

    try {
      // 调用支付成功 API
      const username = getCurrentUsername();
      if (!username) {
        alert('请先登录');
        hide();
        if (resolveCallback) {
          resolveCallback({ success: false, message: '未登录' });
        }
        return;
      }

      const response = await fetch('/api/pay/purchase', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username,
          resourcePath: currentPaymentData.resourcePath,
          categoryDir: currentPaymentData.categoryDir,
          itemName: currentPaymentData.itemName,
          price: currentPaymentData.price
        })
      });

      const result = await response.json();

      if (result.success) {
        // 支付成功，通知父窗口
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'payment-success',
            itemName: currentPaymentData.itemName
          }, '*');
          
          // 通知父窗口关闭支付界面 iframe
          window.parent.postMessage({
            type: 'close-pay-view'
          }, '*');
        }

        // 显示成功提示
        if (window.parent && window.parent.HintView) {
          window.parent.HintView.success('购买成功！文件已添加到网盘', 3000);
        }

        hide();
        if (resolveCallback) {
          resolveCallback({ success: true, result });
        }
      } else {
        // 支付失败
        if (window.parent && window.parent.HintView) {
          window.parent.HintView.error(result.message || '购买失败', 3000);
        }
        
        // 通知父窗口关闭支付界面 iframe
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'close-pay-view'
          }, '*');
        }
        
        hide();
        if (resolveCallback) {
          resolveCallback({ success: false, message: result.message });
        }
      }
    } catch (error) {
      console.error('[PayView] 支付处理失败:', error);
      if (window.parent && window.parent.HintView) {
        window.parent.HintView.error('购买失败，请稍后重试', 3000);
      }
      
      // 通知父窗口关闭支付界面 iframe
      if (window.parent && window.parent !== window) {
        window.parent.postMessage({
          type: 'close-pay-view'
        }, '*');
      }
      
      hide();
      if (resolveCallback) {
        resolveCallback({ success: false, message: error.message });
      }
    }
  }


  // 获取当前登录用户名
  function getCurrentUsername() {
    try {
      const loginDataStr = localStorage.getItem('loginData');
      if (!loginDataStr) {
        return null;
      }
      
      const loginData = JSON.parse(loginDataStr);
      const now = Date.now();
      
      // 检查是否过期
      if (now >= loginData.expireTime) {
        localStorage.removeItem('loginData');
        return null;
      }
      
      return loginData.user ? loginData.user.username : null;
    } catch (error) {
      console.error('[PayView] 获取用户名失败:', error);
      return null;
    }
  }

  // 导出全局函数
  window.PayView = {
    show: show,
    hide: hide
  };

  // 初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

