// Result Page - Handle emblemscanner results and navigation
Page({
  /**
   * Page initial data
   */
  data: {
    ok: false,
    qr_code: '',
    serial_code: '',
    scan_timestamp: '',
    show_verify_failed: false
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    console.log('Result page loaded with options:', options);

    const timestamp = new Date().toLocaleString();
    const ok = options.ok === '1';
    const qr_code = options.qr_code || '';
    const serial_code = options.serial_code || '';

    this.setData({
      ok: ok,
      qr_code: decodeURIComponent(qr_code),
      serial_code: decodeURIComponent(serial_code),
      scan_timestamp: timestamp,
      show_verify_failed: !ok
    });

    console.log('Result page data:', {
      ok: ok,
      qr_code: qr_code,
      serial_code: serial_code
    });

    // Handle navigation based on result
    if (ok && serial_code) {
      // Success case: redirect to productinfo page
      this.redirectToProductInfo(serial_code);
    } else if (!ok) {
      // Failure case: show verify failed UI
      this.showVerifyFailed();
    }
  },

  /**
   * Redirect to product info page with serial code
   */
  redirectToProductInfo(serialCode) {
    console.log('Redirecting to productinfo with serial_code:', serialCode);

    wx.redirectTo({
      url: `/pages/productinfo/productinfo?serial_code=${encodeURIComponent(serialCode)}`,
      success: () => {
        console.log('Successfully redirected to productinfo');
      },
      fail: (err) => {
        console.error('Failed to redirect to productinfo:', err);
        // Fallback: show verify failed UI
        this.showVerifyFailed();
      }
    });
  },

  /**
   * Show verify failed UI
   */
  showVerifyFailed() {
    console.log('Showing verify failed UI');
    this.setData({
      show_verify_failed: true
    });
  },

  /**
   * Handle verifyfailed component back event - rescan
   */
  onVerifyFailedBack() {
    console.log('Verify failed back event - rescanning');
    this.rescan();
  },

  /**
   * Handle verifyfailed component service event
   */
  onVerifyFailedService() {
    console.log('Verify failed service event - showing service modal');
    // You can implement service modal logic here if needed
    // For now, just log it
  },

  /**
   * Rescan - go back to emblemscanner
   */
  rescan() {
    console.log('Rescan button clicked');

    wx.redirectTo({
      url: '/pages/emblemscanner/emblemscanner?return_page=/pages/result_page/result_page',
      success: () => {
        console.log('Successfully redirected to emblemscanner');
      },
      fail: (err) => {
        console.error('Failed to redirect to emblemscanner:', err);
        wx.showToast({
          title: 'Navigation failed',
          icon: 'error'
        });
      }
    });
  },

});