import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import common from '@ohos.app.ability.common';
import { cameraPicker, camera } from '@kit.CameraKit'
import { abilityAccessCtrl } from '@kit.AbilityKit';

@CustomDialog
export struct PhotoActionSheet {
  controller: CustomDialogController;

  // 添加回调函数属性
  private onPhotoSelected: (uri: string) => void = () => {};

  // 修改构造函数
  constructor(controller: CustomDialogController, onPhotoSelected: (uri: string) => void) {
    super();
    this.controller = controller;
    this.onPhotoSelected = onPhotoSelected;
  }

  async checkCameraPermission(): Promise<boolean> {
    const atManager = abilityAccessCtrl.createAtManager();
    const grantStatus = await atManager.checkAccessToken(
      globalThis.abilityContext.applicationInfo.accessTokenId,
      'ohos.permission.CAMERA'
    );
    return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
  }

  build() {
    Column() {
      // 操作按钮区域
      Column() {
        Row() {
          // 拍摄照片按钮
          Column() {
            Image($r('app.media.icon_camera'))
              .width(40)
              .height(40)
            Text('拍摄照片')
              .fontSize(15)
              .margin({top:10})
              .fontColor($r('app.color.main_color'))
          }
          .width('50%')
          .height(80)
          .onClick(() => {
            const context = getContext() as common.UIAbilityContext;
            const cameras = camera.getCameraManager(context).getSupportedCameras();
            cameras.forEach(device => {
              console.log('Camera type:', device.cameraPosition);
            });
            this.openSystemCamera();
            this.animateHide();
          })
          .padding(20)

          // 相册照片按钮
          Column() {
            Image($r('app.media.ixon_album'))
              .width(40)
              .height(40)
            Text('相册照片')
              .fontSize(15)
              .margin({top:10})
              .fontColor($r('app.color.main_color'))
          }
          .width('50%')
          .height(80)
          .onClick(() => {
            this.selectPhoto();
            this.animateHide()
          })
          .padding(20)
        }
      }
      .backgroundColor(Color.White)

      Divider()
        .color('#999999')
        .strokeWidth(5)
        .height(5)
        .margin({top:20})

      // 取消按钮
      Button('取消')
        .width('100%')
        .height(50)
        .fontColor('#999999')
        .backgroundColor(Color.White)
        .onClick(() => this.animateHide())
    }
    .width('100%')
    .height(150)
    .backgroundColor(Color.White)
  }

  animateHide() {
    this.controller.close();
  }

  // 打开相机
  private async openSystemCamera() {
    try {
      const pickerProfile: cameraPicker.PickerProfile = {
        cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
        videoDuration: 15 // 录像时设置最大时长（秒）
      };

      const result = await cameraPicker.pick(
        getContext(),
        [cameraPicker.PickerMediaType.PHOTO], // 可替换为VIDEO
        pickerProfile
      );

      if (result.resultCode === 0) {
        console.log('Photo URI:', result.resultUri);
        // 处理拍摄结果
      }
    } catch (error) {
      console.error('Camera error:', error.code);
    }
  }

  // 资源被选中回调，返回资源的信息，以及选中方式
  private selectPhoto() {
    let photoSelectOptions = new picker.PhotoSelectOptions();
    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber = 1;

    let photoViewPicker = new picker.PhotoViewPicker();
    photoViewPicker.select(photoSelectOptions)
      .then((photoSelectResult) => {
        console.info('PhotoViewPicker.select successfully, photoSelectResult uri: ' +
        JSON.stringify(photoSelectResult));
        if (photoSelectResult.photoUris && photoSelectResult.photoUris.length > 0) {
          this.onPhotoSelected(photoSelectResult.photoUris[0]);
        }
      })
      .catch((err: BusinessError) => {
        console.error('PhotoViewPicker.select failed with err: ' + err);
      });
  }
}
