/**
 * 桌面版（Electron）数据库适配层
 * 替代 app.js 中的 IndexedDB 操作，改用 better-sqlite3（通过 IPC）
 * 所有表名均带 kh_ 前缀
 */

const ElectronDB = {
  // 通用：获取全部数据
  async getAll(table) {
    const result = await window.electronAPI.dbQuery({ table, action: 'getAll', data: {} });
    if (!result.success) throw new Error(result.error);
    return (result.data || []).map(row => ElectronDB._parseRow(row));
  },

  // 通用：获取单条
  async get(table, id) {
    const result = await window.electronAPI.dbQuery({ table, action: 'get', data: { id } });
    if (!result.success) throw new Error(result.error);
    return result.data ? ElectronDB._parseRow(result.data) : null;
  },

  // 通用：保存（新增或更新）
  async put(table, data) {
    const result = await window.electronAPI.dbQuery({ table, action: 'save', data });
    if (!result.success) throw new Error(result.error);
    return result.id || data.id;
  },

  // 通用：删除
  async delete(table, id) {
    const result = await window.electronAPI.dbQuery({ table, action: 'delete', data: { id } });
    if (!result.success) throw new Error(result.error);
    return true;
  },

  // 批量保存
  async bulkSave(table, items) {
    const result = await window.electronAPI.dbQuery({ table, action: 'bulkSave', data: { items } });
    if (!result.success) throw new Error(result.error);
    return true;
  },

  // 登录
  async login(username, password) {
    return await window.electronAPI.dbLogin({ username, password });
  },

  // 解析行：将 JSON 字符串字段反序列化
  _parseRow(row) {
    if (!row) return row;
    const jsonFields = ['business_scope', 'photos', 'owner_users', 'tags', 'images', 'permissions'];
    const parsed = { ...row };
    for (const field of jsonFields) {
      if (parsed[field] && typeof parsed[field] === 'string') {
        try { parsed[field] = JSON.parse(parsed[field]); } catch {}
      }
    }
    return parsed;
  }
};

// 云端同步 API（复用原 api.js 逻辑，但在 Electron 环境中直接调用）
const CloudSync = {
  baseUrl: 'http://www.csplan.cn/kehu/api/',
  isOnline: navigator.onLine,

  async request(endpoint, options = {}) {
    if (!CloudSync.isOnline) {
      throw new Error('当前离线');
    }
    const url = CloudSync.baseUrl + endpoint;
    const config = {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
      ...options
    };
    if (config.body && typeof config.body === 'object') {
      config.body = JSON.stringify(config.body);
    }
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 20000);
    config.signal = controller.signal;
    try {
      const response = await fetch(url, config);
      clearTimeout(timer);
      const text = await response.text();
      try { return JSON.parse(text); }
      catch { throw new Error('服务器返回非JSON: ' + text.substring(0, 100)); }
    } catch (err) {
      clearTimeout(timer);
      throw err;
    }
  },

  // 上传本地数据到云端
  async uploadAll() {
    const tables = [
      { local: 'customers', label: '客户', endpoint: 'customers.php?action=sync', key: 'customers' },
      { local: 'products', label: '产品', endpoint: 'products.php?action=sync', key: 'products' },
      { local: 'scripts', label: '话术', endpoint: 'scripts.php?action=sync', key: 'scripts' },
      { local: 'industry_schemes', label: '方案', endpoint: 'schemes.php?action=sync', key: 'schemes' },
      { local: 'visit_records', label: '回访', endpoint: 'visits.php?action=sync', key: 'records' }
    ];

    let total = 0;
    const errors = [];
    const details = {};

    for (const t of tables) {
      try {
        const data = await ElectronDB.getAll(t.local);
        details[t.label] = data.length;
        if (data.length === 0) continue;
        const body = {};
        body[t.key] = data;
        const result = await CloudSync.request(t.endpoint, { method: 'POST', body });
        if (result.success) {
          total += data.length;
        } else {
          errors.push(t.label + ': ' + (result.error || '未知错误'));
        }
      } catch (err) {
        errors.push(t.label + ': ' + err.message);
      }
    }

    return { success: errors.length === 0, total, errors, details };
  },

  // 从云端下载数据（返回 v2.0 格式的 importData，不直接写本地）
  async downloadAll() {
    const pulls = [
      { endpoint: 'customers.php?action=list',  label: '客户', key: 'data', field: 'customers' },
      { endpoint: 'products.php?action=list',   label: '产品', key: 'data', field: 'products' },
      { endpoint: 'scripts.php?action=list',    label: '话术', key: 'data', field: 'scripts' },
      { endpoint: 'schemes.php?action=list',    label: '方案', key: 'data', field: 'industry_schemes' },
      { endpoint: 'visits.php?action=list',     label: '回访', key: 'data', field: 'visitRecords' }
    ];

    let total = 0;
    const errors = [];
    const details = {};

    // 组装成与 importData() 兼容的 v2.0 格式
    const importData = { version: '2.0' };

    for (const p of pulls) {
      try {
        const result = await CloudSync.request(p.endpoint);
        if (result.success && result[p.key]) {
          const rows = result[p.key];
          importData[p.field] = rows;
          details[p.label] = rows.length;
          total += rows.length;
        } else if (result && !result.success) {
          errors.push(p.label + ': ' + (result.error || '接口返回失败'));
          details[p.label] = 0;
          importData[p.field] = [];
        } else {
          details[p.label] = 0;
          importData[p.field] = [];
        }
      } catch (err) {
        errors.push(p.label + ': ' + err.message);
        details[p.label] = 0;
        importData[p.field] = [];
      }
    }

    return { success: errors.length === 0, total, errors, details, importData };
  }
};

// 网络状态监听
window.addEventListener('online', () => { CloudSync.isOnline = true; });
window.addEventListener('offline', () => { CloudSync.isOnline = false; });
