const { app, BrowserWindow, ipcMain, dialog, shell, Menu, Notification } = require('electron');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');

// ============================
// 全局变量
// ============================
let mainWindow = null;
const DB_PREFIX = 'kh_';
// 数据存储在程序根目录下的 data 文件夹，方便查找和备份
const appRootPath = path.dirname(app.getPath('exe'));
const dbDir = path.join(appRootPath, 'data', 'crv_db');
const dbIndexFile = path.join(dbDir, 'db_index.json');

// ============================
// JSON 文件数据库（纯 Node.js，无需编译）
// ============================
const DB = {
  _cache: {},

  // 确保目录存在
  _ensureDir() {
    if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
  },

  // 获取表文件路径
  _tablePath(table) {
    return path.join(dbDir, `${DB_PREFIX}${table}.json`);
  },

  // 读取表数据
  _readTable(table) {
    const p = this._tablePath(table);
    if (!fs.existsSync(p)) return [];
    try {
      return JSON.parse(fs.readFileSync(p, 'utf8')) || [];
    } catch {
      return [];
    }
  },

  // 写入表数据
  _writeTable(table, rows) {
    this._ensureDir();
    fs.writeFileSync(this._tablePath(table), JSON.stringify(rows, null, 2), 'utf8');
  },

  // 获取全部
  getAll(table) {
    return this._readTable(table);
  },

  // 获取单条
  get(table, id) {
    return this._readTable(table).find(r => r.id === id) || null;
  },

  // 保存（新增或更新）
  save(table, data) {
    const rows = this._readTable(table);
    const now = new Date().toISOString();
    const idx = data.id ? rows.findIndex(r => r.id === data.id) : -1;
    if (idx >= 0) {
      rows[idx] = { ...rows[idx], ...data, updated_at: now };
      this._writeTable(table, rows);
      return data.id;
    } else {
      const newId = data.id || `${table.slice(0,4)}_${Date.now()}_${Math.random().toString(36).substr(2,6)}`;
      const newRow = { ...data, id: newId, created_at: now, updated_at: now };
      rows.unshift(newRow);
      this._writeTable(table, rows);
      return newId;
    }
  },

  // 删除
  delete(table, id) {
    const rows = this._readTable(table).filter(r => r.id !== id);
    this._writeTable(table, rows);
  },

  // 批量保存
  bulkSave(table, items) {
    const rows = this._readTable(table);
    const now = new Date().toISOString();
    const map = {};
    rows.forEach(r => { map[r.id] = r; });
    items.forEach(item => {
      if (!item.id) item.id = `${table.slice(0,4)}_${Date.now()}_${Math.random().toString(36).substr(2,6)}`;
      if (map[item.id]) {
        map[item.id] = { ...map[item.id], ...item, updated_at: now };
      } else {
        map[item.id] = { ...item, created_at: now, updated_at: now };
      }
    });
    this._writeTable(table, Object.values(map));
  }
};

// ============================
// 初始化默认管理员
// ============================
function initDefaultData() {
  DB._ensureDir();
  const users = DB.getAll('users');
  const adminExists = users.find(u => u.username === 'admin');
  if (!adminExists) {
    const pwd = crypto.createHash('md5').update('admin123').digest('hex');
    DB.save('users', {
      id: 'admin_001',
      username: 'admin',
      password: pwd,
      real_name: '管理员',
      role: 'admin',
      status: 'active'
    });
    console.log('默认管理员已创建: admin / admin123');
  }
  console.log('数据库初始化成功，数据目录:', dbDir);
}

// ============================
// 创建主窗口
// ============================
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 1024,
    minHeight: 680,
    title: '客户回访登记系统',
    icon: path.join(__dirname, 'assets', 'icon.ico'),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    },
    backgroundColor: '#f8fafc',
    show: false
  });

  mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    mainWindow.maximize();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  createAppMenu();
}

// ============================
// 应用菜单
// ============================
function createAppMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '导出客户数据',
          accelerator: 'CmdOrCtrl+E',
          click: () => mainWindow && mainWindow.webContents.send('menu-export-customers')
        },
        {
          label: '备份数据',
          click: () => mainWindow && mainWindow.webContents.send('menu-backup')
        },
        { type: 'separator' },
        { label: '退出', role: 'quit' }
      ]
    },
    {
      label: '云端同步',
      submenu: [
        {
          label: '上传到云端',
          accelerator: 'CmdOrCtrl+U',
          click: () => mainWindow && mainWindow.webContents.send('menu-cloud-upload')
        },
        {
          label: '从云端下载',
          accelerator: 'CmdOrCtrl+D',
          click: () => mainWindow && mainWindow.webContents.send('menu-cloud-download')
        }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: '关于',
              message: '客户回访登记系统 v1.0.0',
              detail: '电脑版单机应用\n支持云端数据同步\n数据存储路径: ' + dbDir
            });
          }
        },
        {
          label: '打开数据目录',
          click: () => shell.openPath(dbDir)
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// ============================
// IPC 处理
// ============================

// 数据库操作
ipcMain.handle('db-query', (event, { table, action, data }) => {
  try {
    if (action === 'getAll') {
      return { success: true, data: DB.getAll(table) };
    }
    if (action === 'get') {
      return { success: true, data: DB.get(table, data.id) };
    }
    if (action === 'save') {
      const id = DB.save(table, data);
      return { success: true, id };
    }
    if (action === 'delete') {
      DB.delete(table, data.id);
      return { success: true };
    }
    if (action === 'bulkSave') {
      DB.bulkSave(table, data.items || []);
      return { success: true };
    }
    return { success: false, error: '未知操作' };
  } catch (err) {
    console.error('DB操作错误:', err);
    return { success: false, error: err.message };
  }
});

// 用户登录
ipcMain.handle('db-login', (event, { username, password }) => {
  try {
    const pwd = crypto.createHash('md5').update(password).digest('hex');
    const users = DB.getAll('users');
    const user = users.find(u => u.username === username && u.status === 'active');
    if (!user) return { success: false, error: '用户不存在或已禁用' };
    if (user.password !== pwd) return { success: false, error: '密码错误' };
    const { password: _p, ...safeUser } = user;
    return { success: true, data: safeUser };
  } catch (err) {
    return { success: false, error: err.message };
  }
});

// 保存文件对话框
ipcMain.handle('save-dialog', async (event, { defaultName, filters }) => {
  const result = await dialog.showSaveDialog(mainWindow, {
    defaultPath: path.join(app.getPath('downloads'), defaultName || 'export.xlsx'),
    filters: filters || [{ name: 'Excel', extensions: ['xlsx'] }]
  });
  return result;
});

// 打开文件对话框
ipcMain.handle('open-dialog', async (event, { filters, defaultPath }) => {
  const opts = {
    filters: filters || [{ name: '所有文件', extensions: ['*'] }],
    properties: ['openFile']
  };
  if (defaultPath) opts.defaultPath = defaultPath;
  const result = await dialog.showOpenDialog(mainWindow, opts);
  return result;
});

// 写文件
ipcMain.handle('write-file', async (event, { filePath, data, encoding }) => {
  try {
    if (encoding === 'base64') {
      fs.writeFileSync(filePath, Buffer.from(data, 'base64'));
    } else {
      fs.writeFileSync(filePath, data, encoding || 'utf8');
    }
    return { success: true };
  } catch (err) {
    return { success: false, error: err.message };
  }
});

// 读文件
ipcMain.handle('read-file', async (event, { filePath, encoding }) => {
  try {
    const data = fs.readFileSync(filePath, encoding || 'utf8');
    return { success: true, data };
  } catch (err) {
    return { success: false, error: err.message };
  }
});

// 获取路径
ipcMain.handle('get-paths', () => ({
  userData: userDataPath,
  dbDir,
  downloads: app.getPath('downloads'),
  documents: app.getPath('documents')
}));

// 显示通知
ipcMain.handle('show-notification', (event, { title, body }) => {
  if (Notification.isSupported()) {
    new Notification({ title, body }).show();
  }
});

// ============================
// 云同步数据交换接口
// ============================

// 保存导出的全量数据（由渲染进程从 IndexedDB 读取后调用）
ipcMain.handle('sync-save-export', (event, { data }) => {
  try {
    DB._ensureDir();
    const exportPath = path.join(dbDir, 'sync_export.json');
    fs.writeFileSync(exportPath, JSON.stringify(data, null, 2), 'utf8');
    return { success: true, path: exportPath };
  } catch (e) {
    return { success: false, error: e.message };
  }
});

// 读取同步工具写入的导入数据（渲染进程将其存回 IndexedDB）
ipcMain.handle('sync-load-import', () => {
  try {
    const importPath = path.join(dbDir, 'sync_import.json');
    if (!fs.existsSync(importPath)) return { success: false, error: '没有找到导入文件' };
    const raw = fs.readFileSync(importPath, 'utf8');
    const data = JSON.parse(raw);
    // 读取完删除，避免重复导入
    fs.unlinkSync(importPath);
    return { success: true, data };
  } catch (e) {
    return { success: false, error: e.message };
  }
});

// 获取同步数据目录路径（供同步工具定位）
ipcMain.handle('sync-get-dir', () => ({
  dbDir,
  exportFile: path.join(dbDir, 'sync_export.json'),
  importFile: path.join(dbDir, 'sync_import.json')
}));

// ============================
// 应用生命周期
// ============================
app.whenReady().then(() => {
  initDefaultData();
  createWindow();
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
