import { PhotoHelper } from '@pura/picker_utils'
import { TitleBar } from '../../../../view/TitleBar'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { AppUtil, DisplayUtil, FileUtil } from '@pura/harmony-utils'
import { ToastUtils } from '../../../../utils/ToastUtils'
import { fileIo } from '@kit.CoreFileKit'
import { SaveUtils } from '../../../../utils/SaveUtils'
import { LoadingDialog } from '../../../../dialog/LoadingDialog'
import { DownloadDialog, DownloadStatus } from '../../../../dialog/DownloadDialog'
import { EventConstants } from '../../../../common/EventConstants'
import { TipDialog } from '../../../../dialog/TipDialog'
import { image } from '@kit.ImageKit'
import { ImageUtils } from '../../../../utils/ImageUtils'
import { Luban } from '@ark/luban'

@Entry
@ComponentV2
struct ImageMergePage {
  @Local pixelMap?: image.PixelMap = undefined
  @Local selectedImage?: string = undefined
  @Local imageUris: Array<string> = []
  @Local isSuccess: boolean = false

  private selectedImages: Array<string> = []

  async mergeImage() {
    LoadingDialog.show(this.getUIContext())
    try {
      let pixelArray: Array<image.PixelMap> = []
      let maxWidth = DisplayUtil.getWidth()
      for (let i = 0;i < this.imageUris.length;i++) {
        let compressedUri = await Luban.with(this.imageUris[i]).ignoreBy(100).get()
        const imageSource: image.ImageSource = image.createImageSource(compressedUri[0])
        let decodingOptions: image.DecodingOptions = {
          editable: true,
          desiredPixelFormat: image.PixelMapFormat.RGB_565,
        }
        let pixelMap = imageSource.createPixelMapSync(decodingOptions)
        if (pixelMap) {
          let imageInfo = pixelMap.getImageInfoSync()
          maxWidth = Math.max(imageInfo.size.width)
          pixelArray.push(pixelMap)
        } else {
          ToastUtils.show('处理失败')
          return
        }
      }

      let totalHeight = 0
      let newPixelArray: Array<image.PixelMap> = []
      for (let i = 0;i < pixelArray.length;i++) {
        let pixelMap = pixelArray[i]
        let imageInfo = pixelMap.getImageInfoSync()
        let height = Math.trunc(imageInfo.size.height * maxWidth / imageInfo.size.width)
        let newPixel = await ImageUtils.resizeImage(pixelMap, maxWidth, height)
        newPixelArray.push(newPixel)
        totalHeight += height
      }

      let offScreenCanvas = new OffscreenCanvas(maxWidth, totalHeight)
      let OffScreenContext = offScreenCanvas.getContext('2d')
      let top = 0
      newPixelArray.forEach((pixelMap) => {
        let imageInfo = pixelMap.getImageInfoSync()
        OffScreenContext.drawImage(pixelMap, 0, top, imageInfo.size.width, imageInfo.size.height)
        top += imageInfo.size.height
      })
      this.pixelMap = OffScreenContext.getPixelMap(0, 0, maxWidth, totalHeight)

      this.selectedImage = undefined
      this.imageUris = []
      this.selectedImages = []
      this.isSuccess = true
      ToastUtils.show('处理成功')
    } catch (e) {
      console.error(e)
      ToastUtils.show('处理失败')
    }
    LoadingDialog.dismiss()
  }

  selectPhotos() {
    PhotoHelper.select({
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
      maxSelectNumber: 9,
      preselectedUris: this.selectedImages,
      isOriginalSupported: false,
    })
      .then((result: photoAccessHelper.PhotoSelectResult) => {
        if (result.photoUris.length != 0) {
          this.isSuccess = false
          this.pixelMap = undefined
          this.selectedImages = result.photoUris
          this.imageUris = result.photoUris
          this.selectedImage = result.photoUris[0]
        }
      })
      .catch((e: BusinessError) => {
        ToastUtils.show(e.message)
      })
  }

  showDownloadDialog() {
    DownloadDialog.show(this.getUIContext(), { status: DownloadStatus.COMPLETED, totalSize: 0, progress: 0, totalCount: 1, index: 0, callback: {
      confirm: () => {
        AppUtil.getContext().eventHub.emit(EventConstants.JumpToRecordEvent, 0)
        this.getUIContext().getRouter().back()
      }
    } })
  }

  onBackPress(): boolean | void {
    if (this.isSuccess) {
      TipDialog.show(this.getUIContext(), {title:'温馨提示', content:'图片尚未保存，是否确定退出？', callback: {
        confirm: () => {
          this.getUIContext().getRouter().back()
        }
      }})
      return true
    }
    return false
  }

  build() {
    Column() {
      TitleBar({ title: '长图拼接' })

      Stack() {
        Scroll() {
          Image(this.pixelMap).width('100%').height('auto')
        }
        .height('100%')
        .scrollBar(BarState.Off)
        .visibility(this.pixelMap ? Visibility.Visible : Visibility.None)

        Column() {
          Stack() {
            Stack() {
              Stack() {
                Column() {
                  Image($r('app.media.ic_add_image')).width(40).height(40)
                  Text('请上传图片').fontColor($r('app.color.color_466afd')).fontSize(15).fontWeight(FontWeight.Medium).margin({ top: 8})
                }
              }
              .width('100%')
              .height('100%')
              .onClick(() => {
                this.selectPhotos()
              })
              .visibility(this.imageUris.length !== 0 ? Visibility.None : Visibility.Visible)

              Image(this.selectedImage).width('100%').height('100%')
                .borderRadius(20)
                .visibility(this.imageUris.length === 0 ? Visibility.None : Visibility.Visible)
            }
            .width('100%')
            .aspectRatio(1)
            .borderRadius(20)
            .backgroundColor(Color.White)
            .shadow({radius: 10, color: '#1a9399a1'})
          }
          .width('100%')
          .height('auto')
          .padding({left: 32, right: 32})
          .margin({top: 40})

          Blank().layoutWeight(1)

          Scroll() {
            List({space: 8}) {
              ForEach(this.imageUris, (item: string, index) => {
                ListItem() {
                  RelativeContainer() {
                    Stack() {
                      Image(item).width('100%').height('100%').borderRadius(6)
                      Text(`${index + 1}`)
                        .width(20)
                        .height(20)
                        .textAlign(TextAlign.Center)
                        .fontColor(Color.White)
                        .fontSize(14)
                        .borderRadius(10)
                        .backgroundColor('#99000000')
                    }
                    .width(80)
                    .height(80)
                    .margin({top: 11, right: 11})
                    .borderWidth(1)
                    .borderRadius(6)
                    .borderColor(item === this.selectedImage ? $r('app.color.color_466afd') : Color.Transparent)

                    Image($r('app.media.ic_delete_image')).width(22).height(22)
                      .alignRules({
                        right: {anchor: '__container__', align: HorizontalAlign.End}
                      })
                      .onClick(() => {
                        this.imageUris.splice(index, 1)
                        if (this.imageUris.length === 0) {
                          this.selectedImage = undefined
                        } else {
                          if (item !== this.selectedImage) {
                            this.selectedImage = this.imageUris[0]
                          }
                        }
                      })
                  }
                  .height('100%')
                  .aspectRatio(1)
                }
                .margin({left: index === 0 ? 32 : 0, right: index === 8 ? 32 : 0})
                .onClick(() => {
                  this.selectedImage = item
                })
              })

              if (this.imageUris.length > 0 && this.imageUris.length < 9) {
                ListItem() {
                  Stack() {
                    Column() {
                      Image($r('app.media.ic_add_image')).width(24).height(24)
                      Text('请上传图片').fontColor($r('app.color.color_466afd')).fontSize(10).margin({top: 4})
                    }
                  }
                  .width(80)
                  .height(80)
                  .borderRadius(6)
                  .backgroundColor(Color.White)
                  .margin({top: 11, right: 11})
                }
                .margin({right: 32})
                .onClick(() => {
                  this.selectPhotos()
                })
              }
            }
            .width('100%')
            .scrollBar(BarState.Off)
            .listDirection(Axis.Horizontal)
          }
          .width('100%')
          .height(92)
          .scrollBar(BarState.Off)
          .scrollable(ScrollDirection.Horizontal)
          .margin({bottom: 20})
        }
        .visibility(this.pixelMap ? Visibility.None : Visibility.Visible)
      }
      .layoutWeight(1)

      Stack() {
        Button('确认处理', { type: ButtonType.Capsule, stateEffect: true })
          .width('100%')
          .height(46)
          .fontColor(Color.White)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .backgroundColor($r('app.color.color_466afd'))
          .onClick(() => {
            if (this.imageUris) {
              this.mergeImage()
            } else {
              ToastUtils.show('请上传图片')
            }
          })
          .visibility(!this.isSuccess ? Visibility.Visible : Visibility.None)

        Row() {
          Button({ type: ButtonType.Capsule, stateEffect: true }) {
            Row() {
              Image($r('app.media.ic_reupload')).width(20).height(20)
              Text('重新上传').fontColor($r('app.color.color_466afd')).fontSize(15).fontWeight(FontWeight.Medium)
            }
          }
          .height(46)
          .layoutWeight(1)
          .borderWidth(1)
          .borderColor($r('app.color.color_466afd'))
          .backgroundColor(Color.Transparent)
          .onClick(() => {
            this.selectPhotos()
          })

          Blank().width(9)

          Button({ type: ButtonType.Capsule, stateEffect: true }) {
            Row() {
              Image($r('app.media.ic_download3')).width(20).height(20)
              Text('保存').fontColor(Color.White).fontSize(15).fontWeight(FontWeight.Medium)
            }
          }
          .height(46)
          .layoutWeight(1)
          .backgroundColor($r('app.color.color_466afd'))
          .onClick(() => {
            SaveUtils.savePixelMapToAlbum(this.pixelMap!!)
              .then((saved) => {
                if (saved) {
                  this.pixelMap = undefined
                  this.selectedImage = undefined
                  this.imageUris = []
                  this.selectedImages = []
                  this.showDownloadDialog()
                } else {
                  ToastUtils.show('保存失败')
                }
              })
              .catch((e: BusinessError) => {
                ToastUtils.show('保存失败：' + e.message)
              })
          })
        }
        .visibility(this.isSuccess ? Visibility.Visible : Visibility.None)
      }
      .padding({left: 16, top: 9, right: 16, bottom: 30 })
      .backgroundColor(Color.White)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}