/**
 * 桌面版 App 覆盖层
 * 覆盖 app.js 中使用 IndexedDB 的方法，改用 Electron SQLite（通过 IPC）
 * 同时添加云端上传/下载功能
 */

(function() {
  'use strict';

  // 等待 app 对象初始化完成
  function waitForApp(callback, retries = 50) {
    if (typeof app !== 'undefined') {
      callback();
    } else if (retries > 0) {
      setTimeout(() => waitForApp(callback, retries - 1), 100);
    } else {
      console.error('app 对象未找到');
    }
  }

  waitForApp(function() {

    // ============================================================
    // 覆盖数据库初始化方法
    // ============================================================
    app.initDatabase = async function() {
      console.log('[Desktop] 使用 Electron SQLite 数据库');
      this.dbReady = true;
      await this.loadSettings();
      await this.initLogin();
    };

    // ============================================================
    // 覆盖数据库 CRUD 方法
    // ============================================================
    app.dbGetAll = async function(table) {
      return await ElectronDB.getAll(table);
    };

    app.dbGet = async function(table, id) {
      return await ElectronDB.get(table, id);
    };

    app.dbPut = async function(table, data) {
      return await ElectronDB.put(table, data);
    };

    app.dbDelete = async function(table, id) {
      return await ElectronDB.delete(table, id);
    };

    // ============================================================
    // 覆盖登录方法（使用本地 SQLite 用户表）
    // ============================================================
    app.handleLogin = async function(e) {
      if (e) e.preventDefault();
      const username = document.getElementById('username').value.trim();
      const password = document.getElementById('password').value.trim();
      const errorEl = document.getElementById('loginError');
      errorEl.textContent = '';

      if (!username || !password) {
        errorEl.textContent = '请输入用户名和密码';
        return;
      }

      try {
        const result = await ElectronDB.login(username, password);
        if (result.success) {
          this.currentUser = result.data;
          // 记住密码
          if (document.getElementById('rememberMe').checked) {
            localStorage.setItem('crv_remember_user', username);
            localStorage.setItem('crv_remember_pwd', password);
          } else {
            localStorage.removeItem('crv_remember_user');
            localStorage.removeItem('crv_remember_pwd');
          }
          document.getElementById('loginPage').style.display = 'none';
          document.getElementById('mainApp').style.display = '';
          this.onLoginSuccess();
        } else {
          errorEl.textContent = result.error || '登录失败';
        }
      } catch (err) {
        errorEl.textContent = '登录失败: ' + err.message;
      }
    };

    // ============================================================
    // 添加云端上传功能
    // ============================================================
    app.cloudUpload = async function() {
      if (!CloudSync.isOnline) {
        this.showToast('当前离线，无法上传', 'warning');
        return;
      }
      this.showToast('正在上传数据到云端，请稍候...', 'info');
      try {
        const result = await CloudSync.uploadAll();
        const details = Object.entries(result.details || {})
          .map(([t, n]) => `${t}: ${n} 条`)
          .join('，');
        if (result.success) {
          this.showToast(`上传成功！共 ${result.total} 条${details ? '（' + details + '）' : ''}`, 'success');
        } else {
          const errMsg = result.errors.length > 0 ? result.errors.join('；') : '部分失败';
          this.showToast('上传部分失败: ' + errMsg, 'warning');
        }
      } catch (err) {
        this.showToast('上传失败: ' + err.message, 'error');
      }
    };

    // ============================================================
    // 从云端下载：读取同步工具生成的 sync_import.json，
    // 补充 version 字段后，完全走「导入备份数据」的同一条代码路径
    // （FileReader → 确认弹窗 → dbPut → handleLogout 退出重登）
    // ============================================================
    app.cloudDownload = async function() {
      try {
        // 1. 读取同步工具写入的 dbDir/sync_import.json
        const result = await window.electronAPI.syncLoadImport();
        if (!result.success) {
          this.showToast('未找到 sync_import.json：' + (result.error || '请先用同步工具从云端下载'), 'warning');
          return;
        }

        // 2. 补充 version 字段（同步工具生成的格式缺少这个，importData 需要）
        const importData = result.data;
        if (!importData.version) {
          importData.version = '2.0';
        }

        // 3. 构造 File 对象
        const blob = new Blob([JSON.stringify(importData)], { type: 'application/json' });
        const file = new File([blob], 'sync_import.json', { type: 'application/json' });

        // 4. 直接调「导入备份数据」原函数，一字不改，走完整路径
        //    包含：FileReader 读取 → 解析 JSON → 确认弹窗 → dbPut 写入 → showToast → handleLogout 退出重登
        await this.importData({ files: [file], value: '' });

      } catch (err) {
        this.showToast('下载失败: ' + err.message, 'error');
      }
    };

    // ============================================================
    // 覆盖导出文件方法（使用原生文件保存对话框）
    // ============================================================
    const _origExportCustomersExcel = app.exportCustomersExcel;
    app.exportCustomersExcel = async function() {
      try {
        const result = await window.electronAPI.saveDialog({
          defaultName: '客户数据_' + new Date().toLocaleDateString('zh-CN').replace(/\//g, '-') + '.xlsx',
          filters: [{ name: 'Excel 文件', extensions: ['xlsx'] }]
        });
        if (result.canceled || !result.filePath) return;

        const customers = await this.dbGetAll('customers');
        const wb = XLSX.utils.book_new();
        const header = ['姓名','电话','公司','等级','省份','城市','详细地址','回访周期(天)','下次回访','状态','备注'];
        const rows = customers.map(c => [
          c.name, c.phone, c.company, c.level, c.province, c.city,
          c.detail_address, c.return_days, c.next_visit_date, c.status === 'active' ? '正常' : '停用', c.remark
        ]);
        const ws = XLSX.utils.aoa_to_sheet([header, ...rows]);
        XLSX.utils.book_append_sheet(wb, ws, '客户数据');
        const xlsxData = XLSX.write(wb, { type: 'base64', bookType: 'xlsx' });
        const writeResult = await window.electronAPI.writeFile({
          filePath: result.filePath,
          data: xlsxData,
          encoding: 'base64'
        });
        if (writeResult.success) {
          this.showToast('导出成功: ' + result.filePath, 'success');
        } else {
          this.showToast('导出失败: ' + writeResult.error, 'error');
        }
      } catch (err) {
        this.showToast('导出失败: ' + err.message, 'error');
      }
    };

    // ============================================================
    // 覆盖备份方法
    // ============================================================
    app.exportDataBackup = async function() {
      try {
        const result = await window.electronAPI.saveDialog({
          defaultName: '客户回访系统备份_' + new Date().toLocaleDateString('zh-CN').replace(/\//g, '-') + '.json',
          filters: [{ name: 'JSON 文件', extensions: ['json'] }]
        });
        if (result.canceled || !result.filePath) return;

        const [customers, products, scripts, schemes, visits] = await Promise.all([
          this.dbGetAll('customers'),
          this.dbGetAll('products'),
          this.dbGetAll('scripts'),
          this.dbGetAll('industry_schemes'),
          this.dbGetAll('visit_records')
        ]);

        const backup = {
          version: '2.0',
          exportTime: new Date().toISOString(),
          data: { customers, products, scripts, industry_schemes: schemes, visit_records: visits }
        };

        const writeResult = await window.electronAPI.writeFile({
          filePath: result.filePath,
          data: JSON.stringify(backup, null, 2),
          encoding: 'utf8'
        });
        if (writeResult.success) {
          this.showToast('备份成功: ' + result.filePath, 'success');
          localStorage.setItem('lastBackupTime', new Date().toISOString());
          const el = document.getElementById('lastBackupTime');
          if (el) el.textContent = '上次备份: ' + new Date().toLocaleString('zh-CN');
        } else {
          this.showToast('备份失败: ' + writeResult.error, 'error');
        }
      } catch (err) {
        this.showToast('备份失败: ' + err.message, 'error');
      }
    };

    // ============================================================
    // 监听菜单动作（来自主进程）
    // app.js 已注册过 cloud-upload/cloud-download 处理（走文件中转同步工具），
    // 此处仅覆盖 export-customers 和 backup，避免重复注册导致云同步走错路径。
    // ============================================================
    window.electronAPI.onMenuAction((action) => {
      switch (action) {
        case 'export-customers': app.exportCustomersExcel(); break;
        case 'backup': app.exportDataBackup(); break;
        // cloud-upload / cloud-download 已在 app.js 中正确绑定到
        // syncExportToFile / syncImportFromFile，此处不重复注册
      }
    });

    // ============================================================
    // 云端连接配置
    // ============================================================
    app.loadCloudConfig = function() {
      const saved = localStorage.getItem('crv_cloud_config');
      if (saved) {
        try {
          const cfg = JSON.parse(saved);
          if (cfg.baseUrl) CloudSync.baseUrl = cfg.baseUrl;
        } catch(e) {}
      }
    };

    app.saveCloudConfig = function() {
      const urlInput = document.getElementById('cloudApiUrl');
      if (!urlInput) return;
      let url = urlInput.value.trim();
      if (!url) { this.showToast('请输入API地址', 'warning'); return; }
      if (!url.endsWith('/')) url += '/';
      CloudSync.baseUrl = url;
      localStorage.setItem('crv_cloud_config', JSON.stringify({ baseUrl: url }));
      this.showToast('云端连接信息已保存', 'success');
    };

    app.initCloudDatabase = async function() {
      const btn = document.getElementById('initCloudDbBtn');
      if (btn) { btn.disabled = true; btn.textContent = '初始化中...'; }
      try {
        const result = await CloudSync.request('config.php?init_db=true');
        if (result && (result.success || result.message)) {
          this.showToast('数据库表初始化成功！', 'success');
          const logEl = document.getElementById('cloudInitLog');
          if (logEl) logEl.textContent = (result.message || '初始化完成') + (result.tables ? '\n已创建: ' + result.tables.join(', ') : '');
        } else {
          this.showToast('初始化失败: ' + (result.error || '未知错误'), 'error');
        }
      } catch(err) {
        this.showToast('初始化失败: ' + err.message, 'error');
      } finally {
        if (btn) { btn.disabled = false; btn.textContent = '初始化数据库表'; }
      }
    };

    // 加载云端配置
    app.loadCloudConfig();

    // ============================================================
    // 在设置页面添加云端同步按钮（注入到 DOM）
    // ============================================================
    function injectCloudSyncUI() {
      const settingsDataCard = document.querySelector('#pageSettings .card:nth-child(2) .card-body');
      if (!settingsDataCard) return;

      // 检查是否已经注入
      if (document.getElementById('cloudSyncSection')) return;

      const savedCfg = (() => {
        try { return JSON.parse(localStorage.getItem('crv_cloud_config') || '{}'); } catch(e) { return {}; }
      })();
      const currentUrl = savedCfg.baseUrl || CloudSync.baseUrl;

      const cloudSection = document.createElement('div');
      cloudSection.id = 'cloudSyncSection';
      cloudSection.innerHTML = `
        <div style="border-top: 1px solid #e5e7eb; padding-top: 16px; margin-top: 16px;">
          <h4 style="font-size:15px;font-weight:600;color:#374151;margin-bottom:12px;">
            <i class="fas fa-cloud" style="color:#667eea;margin-right:6px;"></i> 云端连接配置
          </h4>
          <div class="settings-item" style="flex-direction:column;align-items:flex-start;gap:10px;">
            <div style="width:100%;">
              <label style="font-size:13px;color:#6b7280;margin-bottom:4px;display:block;">API 服务器地址</label>
              <div style="display:flex;gap:8px;align-items:center;">
                <input type="text" id="cloudApiUrl" value="${currentUrl}"
                  placeholder="http://www.csplan.cn/kehu/api/"
                  style="flex:1;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;outline:none;">
                <button class="btn btn-primary" onclick="app.saveCloudConfig()" style="white-space:nowrap;">
                  <i class="fas fa-save"></i> 保存
                </button>
              </div>
              <p style="font-size:12px;color:#9ca3af;margin-top:4px;">填写服务器API根目录地址，以 / 结尾</p>
            </div>
            <div style="width:100%;display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
              <button class="btn" onclick="app.initCloudDatabase()" id="initCloudDbBtn"
                style="background:#8B5CF6;color:#fff;">
                <i class="fas fa-database"></i> 初始化数据库表
              </button>
              <span style="font-size:12px;color:#9ca3af;">首次使用前，点击此按钮在服务器上创建所需数据库表</span>
            </div>
            <div id="cloudInitLog" style="font-size:12px;color:#6b7280;background:#f9fafb;border-radius:6px;padding:8px;width:100%;display:none;white-space:pre-wrap;"></div>
          </div>
        </div>
        <div class="settings-item" style="border-top: 1px solid #e5e7eb; padding-top: 16px; margin-top: 4px;">
          <div class="settings-info">
            <h4><i class="fas fa-cloud-upload-alt" style="color:#667eea;"></i> 上传到云端</h4>
            <p>将本地所有数据同步上传到服务器，可供网页版和手机版使用</p>
          </div>
          <button class="btn btn-primary" onclick="app.cloudUpload()">
            <i class="fas fa-cloud-upload-alt"></i> 上传
          </button>
        </div>
        <div class="settings-item">
          <div class="settings-info">
            <h4><i class="fas fa-cloud-download-alt" style="color:#10b981;"></i> 从云端下载</h4>
            <p>从服务器下载最新数据到本地（网页版/手机版数据同步过来）</p>
          </div>
          <button class="btn btn-success" onclick="app.cloudDownload()">
            <i class="fas fa-cloud-download-alt"></i> 下载
          </button>
        </div>
      `;
      // 让 cloudInitLog 在有内容时显示
      cloudSection.querySelector('#initCloudDbBtn').addEventListener('click', function() {
        const log = document.getElementById('cloudInitLog');
        if (log) log.style.display = 'block';
      });
      settingsDataCard.appendChild(cloudSection);
    }

    // 在导航到设置页面时注入
    const _origNavigateTo = app.navigateTo;
    if (typeof _origNavigateTo === 'function') {
      app.navigateTo = function(page) {
        _origNavigateTo.call(this, page);
        if (page === 'settings') {
          setTimeout(injectCloudSyncUI, 200);
        }
      };
    }

    // 初始化后也尝试注入
    setTimeout(injectCloudSyncUI, 2000);

    console.log('[Desktop] 桌面版覆盖层加载完成');
  });

})();
