import { app, shell, BrowserWindow ,ipcMain, screen, dialog} from 'electron'
import { join } from 'path'
import fs from 'fs'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

function createWindow(width, height) {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    icon:icon,
    width,
    height: height,
    center: true,
    show: false,
    transparent:true,
    autoHideMenuBar: true,
    resizable: false,
    titleBarStyle:'hidden',
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation:false,
      webSecurity: false,
    }
  })


  // 处理保存签名请求
  ipcMain.on('save-signature', (event, dataURL) => {
    console.log('保存签名请求:', dataURL);
    console.log('保存event:', event);
    // 从Base64数据中提取图像数据
    const base64Data = dataURL.replace(/^data:image\/png;base64,/, "");
    
    // 弹出保存对话框
    const defaultPath = join(app.getPath('documents'), `signature-${Date.now()}.png`);
    
    dialog.showSaveDialog({
      title: '保存签名图片',
      defaultPath: defaultPath,
      buttonLabel: '保存',
      filters: [{ name: 'PNG图片', extensions: ['png'] }]
    }).then(result => {
      if (!result.canceled && result.filePath) {
        fs.writeFile(result.filePath, base64Data, 'base64', (err) => {
          if (err) {
            console.error('保存签名失败:', err);
            event.sender.send('save-result', {
              success: false, 
              error: err.message
            });
          } else {
            console.log('签名已保存至:', result.filePath);
            event.sender.send('save-result', {
              success: true, 
              path: result.filePath
            });
          }
        });
      }
    }).catch(err => {
      console.error('保存对话框错误:', err);
    });
  })

  // 大屏幕显示
  ipcMain.on('toggle-fullscreen', (event) => {
    if (mainWindow.isFullScreen()) {
      mainWindow.setFullScreen(false)
    } else {
      mainWindow.setFullScreen(true)
    }
  });

  ipcMain.on('minimizing',(event,args)=>{
    event.preventDefault(); // 阻止默认最小化行为
    mainWindow.minimize(); // 最小化到任务栏
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    mainWindow.setFullScreen(true)
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
   // 窗口调试 mainWindow.webContents.openDevTools()
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  // 主进程获取工作区宽高
  const primaryDisplay = screen.getPrimaryDisplay()
  const { width, height } = primaryDisplay.bounds
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow(width, height)

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow(width, height)
  })
})


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