const {
  app,
  BrowserWindow,
  BrowserView,
  Tray,
  Menu,
  nativeImage,
  screen
} = require('electron')

const { resolve } = require('path')

let tray

function createWindow () {
  const mainScreen = screen.getPrimaryDisplay()

  const menuBarHeight = mainScreen.workArea.y

  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 600, // 设置打开的窗口大小
    useContentSize: true,
    enableLargerThanScreen: true,
    autoHideMenuBar: true,
    icon: 'logo.png',
    frame: true, // 显示mac 上顶部的状态栏
    webPreferences: {
      // contextIsolation: false,
      // worldSafeExecuteJavaScript:a flse,
      // webSecurity: false,
      nodeIntegration: true // 是否集成node.js，解决require is not defined问题
      // nodeIntegrationInWorker: true,
      // webviewTag: true, // 解决webview无法显示问题
      // enableRemoteModule: true,
    }
  })

  // mainWindow.setIcon('https://agent-crm.luojigou.vip/crm-api//20210323/logo_icon.png')
  // console.log(resolve(process.cwd(), 'dist/index.html'))
  // mainWindow.loadFile(resolve(process.cwd(), 'dist/index.html'))

  const view = new BrowserView() // new出对象
  mainWindow.setBrowserView(view) // 在主窗口中设置view可用
  view.setBounds({ x: 0, y: 0, width: 1000, height: 600 }) // 定义view的具体样式和位置
  view.setAutoResize({ width: true, height: true })
  view.useContentSize = true

  // 解决mac 顶部的菜单栏高度显示问题
  // const marginTopDiv = document.createElement('div')
  // marginTopDiv.style.height = `${menuBarHeight}px`
  // marginTopDiv.style.width = '100%'
  // document.body.appendChild(marginTopDiv)

  view.webContents.loadURL('http://cloudlink.jiaolongcloud.com') // wiew载入的页面
}

app.whenReady().then(() => {
  const icon = nativeImage.createFromPath('./logo.png')
  tray = new Tray(icon)

  const contextMenu = Menu.buildFromTemplate([])

  tray.setContextMenu(contextMenu)

  tray.setToolTip('This is my application')
  tray.setTitle('This is my title')

  createWindow()
})

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

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