#!/usr/bin/env node
const fs = require("fs").promises;
const path = require("path");
const program = require("commander");

const configFilePath = path.join(__dirname, "..", "project.config.json");
const devFilePath = path.join(__dirname, "..", "config", "dev.js");
const prodFilePath = path.join(__dirname, "..", "config", "prod.js");

/**
 * 项目配置对象
 * 因现在惠融好借和惠融钱包的图片资源都是一样的，所以LOGO和HOME_LOGO暂时这部分代码暂时注释掉
 */

const projectConfigs = {
  hrqb: {
    NAME: "惠融钱包",
    HOST: "https://api.hrshuke.cn",
    appId: "458",
    miniAppId: "wxc7ed88182aa77a68",
    CHANNELCODE: "hrqbxcx",
    LOGO: "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/logo.png",
    HOME_LOGO:
      "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/home_logo_hrqb.png",
  },
  hrhaojie: {
    NAME: "惠融钱包",
    HOST: "https://api.hrshuke.cn",
    appId: "472",
    miniAppId: "wxaca93174bcaa6453",
    CHANNELCODE: "hrhaojie",
    LOGO: "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/logo.png",
    HOME_LOGO:
      "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/home_logo_hrqb.png",
  },
  cyr: {
    NAME: "诚易融",
    HOST: "https://api.hrshuke.cn",
    appId: "480",
    miniAppId: "wxf7762282683395d1",
    CHANNELCODE: "txxcx02",
    LOGO: "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/logo_cyr.png",
    HOME_LOGO:
      "https://comon-image.oss-cn-hangzhou.aliyuncs.com/miniPrograme/home_logo_cyr.png",
  },
};

// 读取并解析 JSON 文件
async function readJsonFile(filePath) {
  try {
    const data = await fs.readFile(filePath, "utf8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`读取文件失败: ${filePath}, 错误: ${error.message}`);
  }
}

// 写入 JSON 文件
async function writeJsonFile(filePath, data) {
  const jsonData = JSON.stringify(data, null, 2);
  try {
    await fs.writeFile(filePath, jsonData, "utf8");
  } catch (error) {
    throw new Error(`写入文件失败: ${filePath}, 错误: ${error.message}`);
  }
}

// 更新配置项在指定文件中
async function updateConfigInFile(
  filePath,
  newName,
  newHOST,
  newAPPID,
  newCHANNELCODE,
  newLOGO,
  newHOME_LOGO
) {
  try {
    let data = await fs.readFile(filePath, "utf8");
    const updates = [
      { key: "NAME: ", value: `'"${newName}"',` },
      { key: "HOST: ", value: `'"${newHOST}"',` },
      { key: "APPID: ", value: `'"${newAPPID}"',` },
      { key: "CHANNELCODE: ", value: `'"${newCHANNELCODE}"',` },
      { key: "LOGO: ", value: `'"${newLOGO}"',` },
      { key: "HOME_LOGO: ", value: `'"${newHOME_LOGO}"',` },
    ];

    let updatedData = data;
    for (const { key, value } of updates) {
      const startIndex = updatedData.indexOf(key);
      if (startIndex !== -1) {
        const lineEndIndex = updatedData.indexOf("\n", startIndex);
        const lineToReplace = updatedData.substring(startIndex, lineEndIndex);
        updatedData = updatedData.replace(lineToReplace, `${key}${value}`);
      } else {
        console.warn(`未找到 ${key.trim()} 在文件中: ${filePath}`);
      }
    }

    if (data !== updatedData) {
      await fs.writeFile(filePath, updatedData, "utf8");
      console.log(`更新成功: ${filePath} 中的 NAME 已更新为 ${newName}`);
      console.log(`更新成功: ${filePath} 中的 HOST 已更新为 ${newHOST}`);
      console.log(`更新成功: ${filePath} 中的 APPID 已更新为 ${newAPPID}`);
      console.log(
        `更新成功: ${filePath} 中的 CHANNELCODE 已更新为 ${newCHANNELCODE}`
      );
      console.log(`更新成功: ${filePath} 中的 LOGO 已更新为 ${newLOGO}`);
      console.log(
        `更新成功: ${filePath} 中的 HOME_LOGO 已更新为 ${newHOME_LOGO}`
      );
    } else {
      console.log(`没有需要更新的内容: ${filePath}`);
    }
  } catch (error) {
    throw new Error(`更新配置文件失败: ${filePath}, 错误: ${error.message}`);
  }
}

// 更新项目配置
async function updateProjectConfig(projectName) {
  const projectConfig = projectConfigs[projectName];

  if (!projectConfig) {
    throw new Error(`无效的项目名称: ${projectName}`);
  }

  // 更新 project.config.json 中的 appid
  const config = await readJsonFile(configFilePath);
  config.appid = projectConfig.miniAppId;
  await writeJsonFile(configFilePath, config);
  console.log(
    `更新成功: ${configFilePath} 中的 appid 已更新为 ${projectConfig.miniAppId}`
  );

  // 更新 dev.js 和 prod.js 中的 APPID
  await Promise.all([
    updateConfigInFile(
      devFilePath,
      projectConfig.NAME,
      projectConfig.HOST,
      projectConfig.appId,
      projectConfig.CHANNELCODE,
      projectConfig.LOGO,
      projectConfig.HOME_LOGO
    ),
    updateConfigInFile(
      prodFilePath,
      projectConfig.NAME,
      projectConfig.HOST,
      projectConfig.appId,
      projectConfig.CHANNELCODE,
      projectConfig.LOGO,
      projectConfig.HOME_LOGO
    ),
  ]);
}

program
  .command("project <projectName>")
  .description("设置项目")
  .action(async (projectName) => {
    try {
      await updateProjectConfig(projectName);
      console.log(
        "---------- 每次执行完mycli命令后,需要重新编译项目！！！ ----------"
      );
    } catch (error) {
      console.error("操作过程中出错:", error.message);
    }
  });

program.parse(process.argv);
