import { ImageUtils } from '@ohos/common/src/main/ets/utils/ImageUtils';
import { TitleBarComponent } from '../view/TitleBarComponent';
import { image } from '@kit.ImageKit';
import { ImageCropper, ImageCropperController } from '@candies/image_cropper';
import * as image_cropper from "@candies/image_cropper";

@Builder
export function LongImageBuilder() {
  LongImageLayout()
}

/**
 * 拼长图页面
 */
@Component
export struct LongImageLayout {
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;
  @State images: image.PixelMap[] = [];

  @State editingIndex: number = -1;
  private cropperController: ImageCropperController = new ImageCropperController();
  @State config: image_cropper.ImageCropperConfig = new image_cropper.ImageCropperConfig(
    {
      maxScale: 8,
      cropRectPadding: image_cropper.geometry.EdgeInsets.all(20),
      controller: this.cropperController,
      initCropRectType: image_cropper.InitCropRectType.imageRect,
      cropAspectRatio: image_cropper.CropAspectRatios.custom,
    }
  );
  @State imageSource: image.ImageSource | undefined = undefined;
  // 生成图片完成标志
  @State generateImageFlag: boolean = false;


  @Builder pixelMapBuilder(pm: image.PixelMap) {
    Image(pm)
      .width('90%')
      .objectFit(ImageFit.Cover)
      .opacity(0.8)
  }

  aboutToAppear(): void {
    this.config.controller = this.cropperController;
    ImageUtils.openMultipleGallery().then(item => {
      if (item) {
        this.images = item;
      }
    })
  }

  build() {
    NavDestination() {
      Stack() {
        Column() {
          // 标题栏
          TitleBarComponent({
            titleName: '拼长图',
            isShowTitle: true,
            isShowBack: true,
            isShowSave: true,
            onSave: () => {
              /* 保存整张长图逻辑 */
              this.generateImageFlag = true;
              setTimeout(async () => {
                try {
                  await ImageUtils.saveImageForID('crop_container');
                } catch (e) {
                  console.error("保存失败: " + e);
                } finally {
                  this.generateImageFlag = false;
                }
              }, 100);
            }
          })

          Scroll() {
            Column() {
              if (this.images.length > 0){
                //有数据展示列表
                Grid() {
                  ForEach(this.images, (pm: image.PixelMap, index: number) => {
                    GridItem() {
                      Stack({ alignContent: Alignment.TopEnd }) {
                        Image(pm)
                          .width('100%')
                          .objectFit(ImageFit.Cover)
                          .parallelGesture(
                            TapGesture().onAction(async () => {
                              this.editingIndex = index;
                              const source = await ImageUtils.pixelMapToImageSource(pm);
                              this.imageSource = source;
                            })
                          )

                        // 删除按钮
                        Image($r('app.media.ic_close')) // 建议用图片图标
                          .width(24).height(24)
                          .margin({ top: 8, right: 8 })
                          .onClick(() => this.images.splice(index, 1))
                          .visibility(this.generateImageFlag ? Visibility.None : Visibility.Visible)
                      }
                    }
                  }, (pm: image.PixelMap, index: number) => {
                    return index + "_" + pm.getPixelBytesNumber();
                  })
                }
                .columnsTemplate('1fr')
                .padding(16)
                .editMode(true)
                .id('crop_container')
              }else{
                //无数据展示占位
                Stack() {
                  Column(){
                    Image($r('app.media.ic_image_pld')).width(120).height(111.2)
                    Text('去相册选一张美照吧~').fontColor('#FFD8D8D8').fontSize(12)
                  }
                }
                .width('80%')
                .height('90%')
                // .aspectRatio(300/420)
                .backgroundColor('#FFFFFFFF')
                .borderColor('#FFD8D8D8')
                .borderWidth(1)
                .onClick(() => {
                  ImageUtils.openMultipleGallery().then(item => {
                    if (item) {
                      this.images = item;
                    }
                  })
                })
              }
            }
          }
          .layoutWeight(1)
          .scrollBar(BarState.Off)
          .align(Alignment.Top)
        }
        .width('100%')
        .height('100%')

        // 裁剪工具层
        if (this.imageSource) {
          Column(){//({ alignContent: Alignment.Bottom }) {
            ImageCropper({
              image: this.imageSource,
              config: this.config
            })
              .width('100%')
              .height('100%')
              .layoutWeight(1)
              .backgroundColor(Color.Black)

            Row() {
              Text('取消')
                .fontColor('#ffb3b1b1')
                .fontSize(16)
                .onClick(() => {
                  this.imageSource = undefined;
                  this.editingIndex = -1;
                })
              Text('确定')
                .fontColor(Color.White)
                .fontSize(16)
                .onClick(async () => {
                  const croppedPm = await this.cropperController.getCroppedImage();
                  if (croppedPm && this.editingIndex !== -1) {
                    this.images.splice(this.editingIndex, 1, croppedPm);
                  }
                  this.imageSource = undefined;
                  this.editingIndex = -1;
                })
            }
            .width('100%')
            .backgroundColor('#ff8f8d8d')
            .padding({ left: 20, right: 20, top:12, bottom: 30 })
            .justifyContent(FlexAlign.SpaceBetween)
          }
          .width('100%')
          .height('100%')
          .zIndex(100)
        }
      }
      .backgroundColor('#FFFFFF')
    }
    .hideTitleBar(true)
  }
}


