export function downloadApkWithJsonPost(apiUrl, requestData) {
  // 下载文件的本地存储路径
  const downloadPath = "_doc/update/";
  const apkFileName = "app.apk";
  const apkFilePath = downloadPath + apkFileName;

  // 显示下载进度
  let downloadTask;
  const progressTip = plus.nativeUI.showWaiting("准备下载更新...");

  try {
    // 确保下载目录存在
    plus.io.resolveLocalFileSystemURL(
      "_doc/",
      function (entry) {
        entry.getDirectory(
          "update",
          { create: true },
          function (dirEntry) {
            startDownload();
          },
          function (err) {
            handleError("创建下载目录失败：" + JSON.stringify(err));
          }
        );
      },
      function (err) {
        handleError("访问存储失败：" + JSON.stringify(err));
      }
    );
  } catch (e) {
    handleError("初始化下载失败：" + e.message);
  }

  function startDownload() {
    // 创建下载任务
    downloadTask = plus.downloader.createDownload(
      apiUrl,
      {
        method: "POST",
        data: JSON.stringify(requestData),
        filename: apkFilePath,
      },
      function (download, status) {
        progressTip.close();

        // 下载完成
        if (status === 200) {
          console.log("下载成功: " + download.filename);
          installApk(download.filename);
        } else {
          handleError("下载失败，状态码: " + status);
        }
      }
    );

    // 设置POST请求头
    downloadTask.setRequestHeader("Content-Type", "application/json");

    // 监听下载进度
    downloadTask.addEventListener("statechanged", function (task, status) {
      switch (task.state) {
        case 1: // 开始
          progressTip.setTitle("开始下载...");
          break;
        case 2: // 已连接到服务器
          progressTip.setTitle("已连接到服务器...");
          break;
        case 3: // 接收数据
          const progress = parseInt(
            (task.downloadedSize / task.totalSize) * 100
          );
          progressTip.setTitle(`正在下载更新包(${progress}%)...`);
          break;
        case 4: // 下载完成
          progressTip.setTitle("下载完成，准备安装...");
          break;
      }
    });

    // 启动下载
    downloadTask.start();
  }

  function handleError(message) {
    if (progressTip) {
      progressTip.close();
    }

    if (downloadTask && downloadTask.state < 4) {
      downloadTask.abort();
    }

    console.error("下载错误：", message);
    plus.nativeUI.alert(message);
  }
}

function installApk(filepath) {
  plus.runtime.install(
    filepath,
    {
      force: true,
    },
    function () {
      plus.nativeUI.alert("更新完成，应用即将重启", function () {
        plus.runtime.restart();
      });
    },
    function (e) {
      plus.nativeUI.alert("安装失败：" + JSON.stringify(e));
    }
  );
}
