import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
import { GlobalContext } from '../utils/GlobalThis';
import fs from '@ohos.file.fs';
import installer from '@ohos.bundle.installer';

import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
import JGRequest from '../utils/Request';


@Entry
@Component
struct TestDownloadPage {
  @State message: string = '下载1111';

  aboutToAppear(): void {


  }

  download = () => {
    let url = "http://10.88.11.200:10000/openharmony/entry.hap"

    try {
      // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
      request.downloadFile(getContext(this), { url: url }).then((data: request.DownloadTask) => {
        let downloadTask: request.DownloadTask = data;
        downloadTask.on('progress', (r, t) => {
          console.log("xxxxxxxxxxxxx", r, t)
        })
      }).catch((err: BusinessError) => {
        console.error(`xxxxxxxxxxxxFailed to request the download. Code: ${err.code}, message: ${err.message}`);
      })
    } catch (err) {
      console.error(`xxxxxxxxxxxxxFailed to request the download. err: ${JSON.stringify(err)}`);
    }

  }

  downloadApp() {

    let _this = this;

    // 下载路径，示例: /data/storage/el2/base/haps/entry/files/org.ohosdev.deviceinfo-v1.0.0.hap
    let filePath = getContext(this).filesDir + '/' + 'packageName' + '-' + '1.0.0' + ".hap";
    console.log("xxxxxxxxxxxx filepath", filePath)
    // 判断文件是否存在
    fs.access(filePath).then((res) => {

      // 不存在，下载并安装
      try {
        console.log("xxxxxxxxxxx  下载")
        request.downloadFile(getContext(this), {
          url: "http://10.88.11.200:10000/openharmony/entry.hap",
          filePath: filePath,
          header: {
            'Content-Type': 'multipart/form-data',
          }
        }).then((downloadTask) => {

          console.log("xxxxxxxxxxxxxxx", JSON.stringify(downloadTask))

          // 监听下载完成
          downloadTask.on('complete', () => {
            console.info('xxxxxxxxxxxxxxxxxxDownload task completed.');
            // 安装应用
            // _this.installApp(filePath);
          });
          downloadTask.on('progress', (r, t) => {
            console.log("xxxxxxxxxxxxx", r, t)
          })
          // // 监听下载失败
          downloadTask.on('fail', (err) => {
            console.info('xxxxxxxxxxx Download task failed. Cause:' + JSON.stringify(err));

          });
        }).catch((err: BusinessError) => {
          console.error('xxxxxxxxxxxxxxxxxxxxxxxxFailed to request the download. Cause: ' + JSON.stringify(err));

        })
      } catch (err) {
        // err.message: bad file path   Download File already exists
        console.error('xxxxxxxxxxx xerr.code : ' + err.code + ', err.message : ' + err.message);

      }

    }).catch((err: BusinessError) => {
      console.info("xxxxxxxxxxx access failed with error message: " + err.message + ", error code: " + err.code);
    });
  }

  downloadAgent = () => {
    let config: request.agent.Config = {
      action: request.agent.Action.DOWNLOAD,
      url: "http://10.88.11.200:10000/openharmony/entry.hap",
      gauge: true,
      overwrite: true,
      // network: request.agent.Network.WIFI,
    };
    request.agent.create(getContext(), config).then((task: request.agent.Task) => {

      task.on('progress', async (progress) => {
        console.warn(`xxxxxxxxxxx   /Request download status ${progress.state}, downloaded ${progress.processed}`);
      })
      task.on('completed', async () => {
        console.warn(`xxxxxxxxxxx  /Request download completed`);
      })
    }).catch((err: BusinessError) => {
      console.info("xxxxxxxxxxx access failed with error message: " + err.message + ", error code: " + err.code);
    });
  }

  // 安装应用 或 更新应用
  installApp(hapPath: string) {
    let hapFilePaths = [hapPath];
    try {
      installer.getBundleInstaller().then(data => {
        data.install(hapFilePaths, {
          userId: 100,
          isKeepData: false,
          installFlag: 1,
        }, err => {
          // if (err) {
          //   console.error('install failed:' + err.message);
          // } else {
          //   console.info('install successfully.');
          //
          // }
        });
      }).catch(() => {
        // console.error('getBundleInstaller failed. Cause: ' + error.message);

      });
    } catch (error) {
      // console.error('getBundleInstaller failed. Cause: ' + error.message);

    }
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.downloadApp()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}