'use strict';

const { Controller } = require('ee-core');
const { shell  } = require('electron');
const { dialog } = require('electron');
const fs = require('fs');
const path = require('path');
const CoreWindow = require('ee-core/electron/window');
const { BrowserWindow, Menu } = require('electron');
const errData = {
  msg :'请求失败，请联系管理员',
  code:999
}


/**
 * example
 * @class
 */
class UtilsController extends Controller {

  constructor(ctx) {
    super(ctx);
  }


  /**
   * 所有方法接收两个参数
   * @param args 前端传的参数
   * @param event - ipc通信时才有值。详情见：控制器文档
   */

  /**
   * upload
   */
  async shellFun (params) {
    shell[params.action](params.params)
  }


  async openMain (config) {
    if( this.app.electron[config.id]) return;
    const win = new BrowserWindow({
      ...config,

      webPreferences: {
        contextIsolation: false, // false -> 可在渲染进程中使用electron的api，true->需要bridge.js(contextBridge)
        nodeIntegration: true,
        preload: path.join('../preload/bridge.js'),
      },
    });
    win.loadURL(config.url); // 设置窗口的 URL
    // 监听窗口关闭事件

    win.webContents.openDevTools(config.openDevTools);
    win.on('close', () => {
      delete this.app.electron[config.id]; // 删除窗口引用
    });

    this.app.electron[config.id] = win ;

  }

  async openDirectory(optiops={
    title:"选择文件夹"
    }){
    const filePaths = dialog.showOpenDialogSync({
      title:optiops.title || '选择文件夹',
      properties: ['openDirectory']
    })
    if(filePaths[0]) return filePaths[0];
    return filePaths
  }

  async openImage(
      optiops= {
        title:"选择图片",
        filters:[
          { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
        ],
      }
   ){

        const filePaths = dialog.showOpenDialogSync({
          title:optiops.title || '选择图片',
          properties:['openFile'],
          filters:optiops.filters || [
            { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
          ]
        })
        const filePath = filePaths[0];
        const fileBuffer = fs.readFileSync(filePath);
        const base64Image = fileBuffer.toString('base64');
    // 获取文件扩展名
    const extension = path.extname(filePath).toLowerCase().replace('.', '');

    // 根据扩展名确定 MIME 类型
    let mimeType = '';
    switch (extension) {
      case 'jpg':
      case 'jpeg':
        mimeType = 'image/jpeg';
        break;
      case 'png':
        mimeType = 'image/png';
        break;
      case 'gif':
        mimeType = 'image/gif';
        break;
      default:
        mimeType = 'application/octet-stream'; // 默认 MIME 类型
        break;
    }

    // 构建 data URL
    const dataUrl = `data:${mimeType};base64,${base64Image}`;
        return {
          filePath:filePath,
          base64Image:dataUrl
        };
  }
  async openFile(optiops= {
    title:"选择文件",
    filters:[
      { name: '支持JPG', extensions: ['jpg','jpeg'] },
    ],
  }){

    const filePaths = dialog.showOpenDialogSync({
      title:optiops.title || '选择文件',
      properties: ['openFile'],
      filters: optiops.filters || [
        { name: '选择文件' },
      ]
    })
    if(filePaths[0]) return filePaths[0];
    return filePaths

  }


}

UtilsController.toString = () => '[class ExampleController]';
module.exports = UtilsController;
