import web_webview from '@ohos.web.webview';
import process from '@ohos.process'
import common from '@ohos.app.ability.common';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import bundleManager from '@ohos.bundle.bundleManager';
import picker from '@ohos.file.picker';
import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
import fs from '@ohos.file.fs';
import { ProgressDialog } from '../components/ProgressDialog';
import router from '@ohos.router';
import uploadInstance from '../utils/UploadUtil';
import { GlobalContext } from '../utils/GlobalThis';


@Entry
@Component
struct Index {
  UIAbilityContext: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
  dialogController: CustomDialogController = new CustomDialogController({
    builder: ProgressDialog({
      // cancel: ()=> { this.onCancel() },
      // confirm: ()=> { this.onAccept() },
    }),
    alignment: DialogAlignment.Center,
    customStyle: true,
  })

  aboutToAppear(): void {
    this.openGallery()
  }

  private async openGallery() {

    let atManager = abilityAccessCtrl.createAtManager();
    let info = await bundleManager.getBundleInfoForSelf(0);
    if (info && info.appInfo) {
      let result = atManager.verifyAccessTokenSync(info.appInfo.accessTokenId, "ohos.permission.READ_MEDIA");
      if (abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED == result) {
        console.log("has permission")
      }
    } else {
      atManager.requestPermissionsFromUser(this.UIAbilityContext, ["ohos.permission.READ_MEDIA"], (error, result) => {
        if (result) {
          console.log("result: " + JSON.stringify(result));
          if (result.authResults[0] == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
            // 用户授予权限
            this.openGalleryInternal();
          } else {
            // 用户拒绝权限
            console.log("permission denied")
          }
        } else {
          console.log("error: " + JSON.stringify(error));
        }
      });
    }
  }

  private openGalleryInternal() {
    let photoPicker = new picker.PhotoViewPicker();
    photoPicker.select({
      MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
      maxSelectNumber: 1
    }, (error, result) => {
      if (result.photoUris && result.photoUris.length > 0) {
        let totalCount = result.photoUris.length
        let completeCount = 0
        this.dialogController.open()
        // this.uploadImage(result.photoUris); file://media/Photo/3/IMG_1723222627_002/IMG_20240810_005707.jpg
        result.photoUris.forEach((url) => {
          // console.log("uploadLog: 选择完图片的路径" + url);
          uploadInstance.startUpload(url, () => {
            completeCount = completeCount + 1
            if (completeCount >= totalCount) {
              this.dialogController.close()
              router.back()
            }
          })
        })
      }
    });
  }

  build() {
    Column() {

      Row() {
        Image($r("app.media.back_white")).width(20).height(20)
        Text("返回").fontColor(Color.White).fontSize(20).margin({ left: 5 })

        Text("再次选择").fontColor(Color.White).fontSize(20).margin({ left: 20 })
          .onClick(() => {
            this.openGallery()
          })
      }
      .align(Alignment.Start)
      .position({ x: 10, y: 10 })
      .onClick(() => {
        router.back()
      })

    }
    .width('100%')
    .height('100%')
    .backgroundColor($r("app.color.gray_bg"))

  }
}