const BaseAction = require('../core/base-action');

/**
 * 滚动动作 - 页面滚动操作
 * 
 * 支持多种滚动方式：
 * 1. 滚动到底部
 * 2. 滚动到顶部
 * 3. 滚动到指定元素
 * 4. 滚动指定距离
 * 
 * Example:
 * - action: scroll
 *   type: bottom
 * 
 * - action: scroll
 *   type: element
 *   selector: '#submit-button'
 * 
 * - action: scroll
 *   type: distance
 *   x: 0
 *   y: 500
 */
class ScrollAction extends BaseAction {
  async execute() {
    const {
      type = 'bottom',
      selector,
      x = 0,
      y = 0,
      behavior = 'smooth'
    } = this.config;
    
    this.log('debug', `执行滚动: ${type}`);
    
    switch (type) {
      case 'bottom':
        await this.scrollToBottom(behavior);
        break;
      
      case 'top':
        await this.scrollToTop(behavior);
        break;
      
      case 'element':
        if (!selector) {
          throw new Error('滚动到元素需要提供 selector');
        }
        await this.scrollToElement(selector, behavior);
        break;
      
      case 'distance':
        await this.scrollByDistance(x, y, behavior);
        break;
      
      default:
        throw new Error(`不支持的滚动类型: ${type}`);
    }
    
    // 等待滚动完成
    await new Promise(resolve => setTimeout(resolve, 500));
    
    this.log('debug', '✓ 滚动完成');
    
    return { success: true };
  }
  
  /**
   * 滚动到页面底部
   */
  async scrollToBottom(behavior) {
    await this.page.evaluate((b) => {
      window.scrollTo({
        top: document.body.scrollHeight,
        left: 0,
        behavior: b
      });
    }, behavior);
  }
  
  /**
   * 滚动到页面顶部
   */
  async scrollToTop(behavior) {
    await this.page.evaluate((b) => {
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: b
      });
    }, behavior);
  }
  
  /**
   * 滚动到指定元素
   */
  async scrollToElement(selector, behavior) {
    const element = await this.page.$(selector);
    
    if (!element) {
      throw new Error(`元素不存在: ${selector}`);
    }
    
    await element.evaluate((el, b) => {
      el.scrollIntoView({
        behavior: b,
        block: 'center',
        inline: 'nearest'
      });
    }, behavior);
  }
  
  /**
   * 滚动指定距离
   */
  async scrollByDistance(x, y, behavior) {
    await this.page.evaluate((dx, dy, b) => {
      window.scrollBy({
        top: dy,
        left: dx,
        behavior: b
      });
    }, x, y, behavior);
  }
}

module.exports = ScrollAction;
