import router from '@ohos.router'
import common from '@ohos.app.ability.common'
import CameraService from '../model/CameraService'
import Logger from '../utils/Logger'
import { GlobalContext } from '../utils/GlobalThis'
import promptAction from '@ohos.promptAction'
import { BusinessError } from '@ohos.base'
import http from '@ohos.net.http'
import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
import fs from '@ohos.file.fs';
import { ProgressDialog } from '../components/ProgressDialog';
import uploadInstance from '../utils/UploadUtil'

const TAG = "uploadTagegggg"

@Entry
@Component
struct Index {
  private mXComponentController: XComponentController = new XComponentController()
  @State surfaceId: number = 0;
  @State cameraDeviceIndex: number = 0
  @State assetUri?: string = undefined //拍照返回的
  @State thumbnail: PixelMap | undefined = undefined //录像返回的
  @State isTakePictureEnabled: boolean = true
  @State isTakeVideoEnabled: boolean = true
  @State captureBtnScale: number = 1
  @State isUploading: boolean = false

  async aboutToAppear() {
    CameraService.setTakePictureCallback((assetUri: string): void => this.handleTakePicture(assetUri))
    Logger.info(TAG, `takePicture end, assetUri: ${this.assetUri}`)
  }

  async cameraInit() {
    CameraService.initCamera(this.surfaceId, this.cameraDeviceIndex).then(() => {
    })
  }

  handleTakePicture(assetUri: string) {
    this.assetUri = assetUri
    // Logger.info(TAG, `takePicture end, assetUri: ${this.assetUri}`)

    this.isUploading = true
    uploadInstance.startUpload(assetUri, () => {
      this.isUploading = false
      this.assetUri = ""
      console.log(TAG, "上传完成后的callback")
    })


  }

  onPageShow() {
    let SurfaceId: string = this.mXComponentController.getXComponentSurfaceId()
    this.surfaceId = Number.parseInt(SurfaceId)
    CameraService.initCamera(this.surfaceId, this.cameraDeviceIndex)
    Logger.info(TAG, `OnPageShow this.cameraDeviceIndex ${this.cameraDeviceIndex}`)
  }

  onPageHide() {
    CameraService.releaseCamera()
    Logger.info(TAG, `onPageHide releaseCamera end`)
  }

  build() {
    Stack({ alignContent: Alignment.BottomEnd }) {
      XComponent({
        id: 'componentId',
        type: 'surface',
        controller: this.mXComponentController
      })
        .size({ width: '100%', height: '100%' })
        .onLoad(async () => {
          Logger.info(TAG, 'onLoad is called')
          let SurfaceId: string = this.mXComponentController.getXComponentSurfaceId()
          this.surfaceId = Number.parseInt(SurfaceId)
          Logger.info(TAG, `onLoad surfaceId: ${this.surfaceId}`)
          this.cameraInit()
        })

      // 拍照完成后显示的image。
      Row() {
        if (this.assetUri !== undefined) {

          Stack({ alignContent: Alignment.Center }) {
            Image(this.assetUri)
              .size({ height: '100%' })
              .border({ width: 1, color: Color.White })
            if (this.isUploading) {
              Column() {
                Text('正在上传中...').fontSize(22).margin({ top: 10, bottom: 10 })
                LoadingProgress()
                  .color(Color.Blue)
                  .layoutWeight(1)
              }
              .height(140)
              .width(150)
              .backgroundColor(Color.White)
              .borderRadius(10)
            }
          }
        }

      }.size({ width: '100%', height: '30%' }).justifyContent(FlexAlign.SpaceBetween)

      Row() {
        Stack({ alignContent: Alignment.Center }) {
          Image($r('app.media.ic_circled')).fillColor(Color.White)
          Image($r('app.media.ic_circled_filled'))
            .width(54)
            .aspectRatio(1)
            .fillColor(Color.White)
            .scale({ x: this.captureBtnScale, y: this.captureBtnScale, z: this.captureBtnScale })
            .enabled(this.isTakePictureEnabled)
            .onTouch(async (event: TouchEvent) => {
              if (event.type === TouchType.Down) {
                animateTo(
                  { duration: 125, curve: Curve.Sharp, delay: 0 },
                  () => {
                    this.captureBtnScale = 0.85
                  })
              } else if (event.type === TouchType.Up) {
                animateTo(
                  { duration: 125, curve: Curve.Sharp, delay: 0,
                    onFinish: () => {
                      this.captureBtnScale = 1
                    } },
                  () => {
                    this.captureBtnScale = 1
                  })
                this.isTakePictureEnabled = false
                CameraService.takePicture()
                this.isTakePictureEnabled = true
              }
            })
        }.width(76).aspectRatio(1)
      }.size({ width: '100%', height: 76 }).justifyContent(FlexAlign.Center)

      Row() {
        Image($r("app.media.back_white")).width(20).height(20)
        Text("返回").fontColor(Color.White).fontSize(20).margin({ left: 5 })
      }
      .position({ x: 10, y: 10 })
      .onClick(() => {
        router.back()
      })

    }.width('100%').height('100%').backgroundColor(Color.Black)
    .gesture(
      PanGesture({ direction: PanDirection.Left | PanDirection.Right })
        .onActionEnd(() => {
          router.back()
        })
    )
  }
}