
import i18n from './configs/i18next.config';
import { app, BrowserWindow, Menu, webContents, ipcMain, dialog } from 'electron';
import { installExtensions } from '../gui-common/debug';
import { setupMainWindow } from '../gui-common/windows';
import { rebuildMenus } from './main/menus';
import settings from './shared/settings';
import { APPIUM_SESSION_EXTENSION, getAppiumSessionFilePath } from './main/helpers';
import path from 'path';
import fs from 'fs';
import JsWdIoFramework from './renderer/lib/client-frameworks/js-wdio';
const {exec} = require('child_process');
import {Interaction, TestPlatform} from 'appium-data-interaction';

let mainWindow = null;
const isDev = process.env.NODE_ENV === 'development';

if (isDev) {
  require('electron-debug')(); // eslint-disable-line global-require
}

let openFilePath = getAppiumSessionFilePath(process.argv, app.isPackaged, isDev);

app.on('open-file', (event, filePath) => {
  openFilePath = filePath;
});

app.on('window-all-closed', () => {
  app.quit();
});

function buildSessionWindow () {
  TestPlatform.setInfo('http://localhost:8888',
    'experimentation_subject_id=imuzndu1mdjkltuwmdctndk2ys1hmtljlti1owrlnjc4yzfmosi%3d--fb98d346787f918849a9c9f856a783933b9fbe94; sensorsdata2015jssdkcross=%7b%22distinct_id%22%3a%22cwmsvtiu%22%2c%22%24device_id%22%3a%221818b7939df5b9-0e4072c3066eed-1d525635-1930176-1818b7939e01c4e%22%2c%22props%22%3a%7b%22%24latest_referrer%22%3a%22%22%2c%22%24latest_traffic_source_type%22%3a%22%e7%9b%b4%e6%8e%a5%e6%b5%81%e9%87%8f%22%2c%22%24latest_search_keyword%22%3a%22%e6%9c%aa%e5%8f%96%e5%88%b0%e5%80%bc_%e7%9b%b4%e6%8e%a5%e6%89%93%e5%bc%80%22%7d%2c%22first_id%22%3a%221818b7939df5b9-0e4072c3066eed-1d525635-1930176-1818b7939e01c4e%22%2c%22identities%22%3a%22eyikawrlbnrpdhlfy29va2llx2lkijoimtgzmgi2mmnlmwyymdqtmdc0zwuzyjiyztdlogy4ltfinti1njm1lte5mzaxnzytmtgzmgi2mmnlmjaxyzg3iiwijglkzw50axr5x2xvz2lux2lkijoiq3dnc3z0avuifq%3d%3d%22%2c%22history_login_id%22%3a%7b%22name%22%3a%22%24identity_login_id%22%2c%22value%22%3a%22cwmsvtiu%22%7d%7d; remember_token=6406f1f672e4efcd4d47d36a|2715bd37fbd1a85bf9604019b6c5e81b0a65ef56f0f58f90ddc55b6b2e7b82e73ec866863cf358339e80d0b60d7f21ddcce9ee80d47879e9a045ed8bd13beb7f; session=.ejwdyzsoajemang7pkawhcdjuazyv9duqow4o4hypdfv9jrzud2ixzswsghjpoqsdw6e0uxbpd3qyppers_jlb_6c8wxmxn73ds5azkvdz6oi5eyvuipjy30nhlb-hswqo5ftrhvezurosuog16mmx227tadoyvloyapdakbxwbzap5wxvju7fmfh0020g.zcer_g.cq9eqooxjtrerz589dhvixjvkqe; auto-ftest=eyjhbgcioijiuzuxmiisimlhdci6mty3otg5ntu1mcwizxhwijoxnjc5otaynzuwfq.eyjlbwfpbci6innozw5szwlazm9yew91ntyuy29tiiwicm9szxmiolsichjvamvjdcisinvzzxiilcjhzg1pbijdlcjuyw1lijoi5rki6zu3iiwibw9iawxlijoimtm2mdawmdawmdaifq.s7ghd-yfdtpkva1qog8f2x9-qw8j9thdpglaekvl-oz3o98gkgwpve1g1u8pig0bsihghirh_9p_4zzikizdoq; auto-ftest=eyjhbgcioijiuzuxmiisimlhdci6mty3otg5ntu1mcwizxhwijoxnjc5otaynzuwfq.eyjlbwfpbci6innozw5szwlazm9yew91ntyuy29tiiwicm9szxmiolsichjvamvjdcisinvzzxiilcjhzg1pbijdlcjuyw1lijoi5rki6zu3iiwibw9iawxlijoimtm2mdawmdawmdaifq.s7ghd-yfdtpkva1qog8f2x9-qw8j9thdpglaekvl-oz3o98gkgwpve1g1u8pig0bsihghirh_9p_4zzikizdoq; auth-token=eyjhbgcioijiuzuxmiisimlhdci6mty3otg5ntu1mcwizxhwijoxnjc5otaynzuwfq.eyjlbwfpbci6innozw5szwlazm9yew91ntyuy29tiiwicm9szxmiolsichjvamvjdcisinvzzxiilcjhzg1pbijdlcjuyw1lijoi5rki6zu3iiwibw9iawxlijoimtm2mdawmdawmdaifq.s7ghd-yfdtpkva1qog8f2x9-qw8j9thdpglaekvl-oz3o98gkgwpve1g1u8pig0bsihghirh_9p_4zzikizdoq');

  const window = new BrowserWindow({
    show: false,
    width: 1280,
    height: 800,
    minWidth: 1000,
    minHeight: 800,
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      additionalArguments: openFilePath ? [`filename=${openFilePath}`] : [],
    },
  });

  ipcMain.on('make-request', async (event, args) => {
    const {requestName} = JSON.parse(args);
    try {
      if (requestName === 'getSuiteGroupList') {
        const response = await TestPlatform.getSuiteGroupList('641a7505211af6db9e160825');
        const convertResponse = convertData(response);
        const params = {requestName, convertResponse};
        event.reply('receive-request', JSON.stringify(params));
      } else if (requestName === 'testSuiteList') {
        const { groupId, skip } = JSON.parse(args);
        const response = await TestPlatform.getTestSuiteList('641a7505211af6db9e160825', groupId, skip);
        const convertResponse = {'total': response.data.totalNum, 'rows': convertData(response)};
        const params = {requestName, convertResponse};
        event.reply('receive-request', JSON.stringify(params));
      } else if (requestName === 'testSuiteEnv') {
        const response = await TestPlatform.getTestEnvList();
        const convertResponse = convertData(response);
        const params = {requestName, convertResponse};
        event.reply('receive-request', JSON.stringify(params));
      } else if (requestName === 'startUIAutomation') {
        const {suiteVars, testId, envId } = JSON.parse(args);
        const response = await TestPlatform.startUIAutomationTest(suiteVars, [testId], '641a7505211af6db9e160825', envId);
        const params = {requestName, response};
        event.reply('receive-request', JSON.stringify(params));
      }
    } catch (e) {
      event.reply('receive-request', e);
    }

  });

  // eslint-disable-next-line require-await
  ipcMain.on('get-appdata', async (event, args) => {

    const {caps, apiPath, responseName } = JSON.parse(args);
    Interaction.setCaps(caps, 'http://localhost:8084');
    try {
      let response = await Interaction.getAppData(apiPath);
      const e = null;
      const params = {responseName, response, e};
      event.reply('receive-appdata', JSON.stringify(params));
    } catch (e) {
      const response = null;
      const params = {responseName, response, e};
      event.reply('receive-appdata', JSON.stringify(params));
    }
  });

  ipcMain.on('select-script', async (event) => {
    const options = {
      title: 'Select File', // 对话框标题
      buttonLabel: 'Select', // 按钮文本
      filters: [
        { name: 'JS Files', extensions: ['js'] }// 文件类型过滤器
      ],
      properties: ['openFile'] // 属性配置
    };
    const result = await dialog.showOpenDialog(options);
    if (!result.canceled) {
      const filePath = result.filePaths[0];
      const script = fs.readFileSync(filePath, 'utf-8');
      const params = {filePath, script};
      event.reply('send-script', JSON.stringify(params));
    }
  });

  // eslint-disable-next-line require-await
  ipcMain.on('execute-script', async (event, args) => {

    const jsonArgs = JSON.parse(args);
    const { newExecuteVars, host, port, spath, https, caps, cookie, filePath} = jsonArgs;
    const script = fs.readFileSync(filePath, 'utf-8');
    const executeScript = new JsWdIoFramework(host, port, spath, https, caps, filePath, cookie, newExecuteVars).wrapWithBoilerplate(script);
    console.log(`executeScript = ${executeScript}`);
    eval(executeScript);

  });
  ipcMain.on('save-script', (event, args) => {
    const { actions } = args;
    // const fileDir = path.join(app.getPath('userData'), '/Script');
    // const filePath = path.join(app.getPath('userData'), '/Script/' + scriptName + '.js');
    //
    // // 检查目录是否存在
    // fs.access(fileDir, fs.constants.F_OK, (err) => {
    //   if (err) {
    //     // 目录不存在 尝试创建
    //     fs.mkdir(fileDir, {recursive: true}, (err) => {
    //       if (err) {
    //         console.error(`Error creating directory: ${err}`);
    //       } else {
    //         console.log(`Directory ${fileDir} created successfully!`);
    //         fs.writeFile(filePath, actions, (err) => {});
    //       }
    //     });
    //   } else {
    //     fs.writeFile(filePath, actions, (err) => {});
    //   }
    // });
    const options = {
      title: 'Save File', // 对话框标题
      buttonLabel: 'Save', // 按钮文本
      filters: [
        { name: 'JS Files', extensions: ['js'] }// 文件类型过滤器
      ]
    };
    dialog.showSaveDialog(options).then((result) => {
      if (!result.canceled) {
        const filePath = result.filePath;
        fs.writeFile(filePath, actions, (err) => {});
        console.log('保存文件路径:', filePath);
        // 在这里处理文件保存逻辑，将数据写入文件等
      } else {
        console.log('用户取消了保存操作');
      }
    }).catch((err) => {
      console.error('保存文件对话框错误:', err);
    });
  });
  ipcMain.on('save-file-as', async () => {
    const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
      title: 'Save Appium File',
      filters: [
        {name: 'Appium Session Files', extensions: [APPIUM_SESSION_EXTENSION]},
      ]
    });
    if (!canceled) {
      mainWindow.webContents.send('save-file', filePath);
    }
  });
  return window;
}

function launchAppiumServer () {
  // 启动appium server
  exec(`appium --log-level=debug --base-path='/wd/hub'`, async (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing shell script: ${error}`);
      return;
    }

    console.log('Shell script output:', stdout);
  });
}

export function launchNewSessionWindow () {
  const url = `file://${__dirname}/index.html`;
  const win = buildSessionWindow();
  win.loadURL(url);
  win.show();
}

app.on('ready', async () => {
  await installExtensions();

  mainWindow = buildSessionWindow();

  const splashWindow = new BrowserWindow({
    width: 300,
    height: 300,
    minWidth: 300,
    minHeight: 300,
    frame: false,
  });

  launchAppiumServer();

  setupMainWindow({
    mainWindow,
    splashWindow,
    mainUrl: `file://${__dirname}/index.html`,
    splashUrl: `file://${__dirname}/splash.html`,
    isDev,
    Menu,
    i18n,
    rebuildMenus,
    settings,
    webContents,
    shouldShowFileMenu: true,
  });
});

function convertData (originalData) {
  const convertedData = [];
  for (const originalItem of originalData.data.rows) {
    const convertedItem = {
      key: originalItem._id,
      label: originalItem.name,
    };
    if (originalItem.children) {
      convertedItem.children = convertChildren(originalItem.children);
    }
    convertedData.push(convertedItem);
  }
  return convertedData;
}

function convertChildren (originalChildren) {
  const convertedChildren = [];
  for (const originalChild of originalChildren) {
    const convertedChild = {
      key: originalChild._id,
      label: originalChild.name,
    };
    if (originalChild.children && originalChild.children.length > 0) {
      convertedChild.children = convertChildren(originalChild.children);
    }
    convertedChildren.push(convertedChild);
  }
  return convertedChildren;
}