import { PhotoHelper } from '@pura/picker_utils'
import { UploadImgEntity } from '../../../../../entity/UploadImgEntity'
import { AddImageItemView } from '../../../../../view/AddImageItemView'
import { TitleBar } from '../../../../../view/TitleBar'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { ToastUtils } from '../../../../../utils/ToastUtils'
import { StrUtil } from '@pura/harmony-utils'
import { FeedbackViewModel } from '../../../../../viewModel/FeedbackViewModel'

enum FeedbackType {
  SUGGESTION, BUG, OTHER
}

@Entry
@ComponentV2
struct FeedbackPage {
  @Local type: FeedbackType = FeedbackType.SUGGESTION
  @Local contentText: string = ''
  @Local contactText: string = ''
  @Local selectedPhotos: Array<string> = []

  selectedUris: Array<string> = []
  selectedImages: Array<UploadImgEntity> = []

  viewModel: FeedbackViewModel = new FeedbackViewModel(this.getUIContext())

  @Monitor('viewModel.feedback')
  onFeedbackChange(monitor: IMonitor) {
    ToastUtils.show('提交成功')
    this.getUIContext().getRouter().back()
  }

  commit() {
    if (StrUtil.isEmpty(this.contentText)) {
      ToastUtils.show('请输入详情内容')
      return
    }
    const typeStr = this.type === FeedbackType.SUGGESTION ? '产品建议' : this.type === FeedbackType.BUG ? '功能异常' : '其他问题'
    if (this.selectedPhotos.length > 0) {
      this.viewModel.uploadImages(this.selectedPhotos)
        .then((uploadImages) => {
          this.viewModel.sendFeedback(typeStr, this.contentText, this.contactText, uploadImages)
        })
    } else {
      this.viewModel.sendFeedback(typeStr, this.contentText, this.contactText, [])
    }
  }

  build() {
    Column() {
      TitleBar({ title: '意见反馈' })

      Scroll() {
        Column() {
          Row() {
            Text('请选择您要反馈的问题').fontColor($r('app.color.color_90ffffff')).fontSize(14)
            Text('*').fontColor('#FF3838')
          }
          .width('100%')

          Row() {
            Button('产品建议', { type: ButtonType.Normal })
              .height(32)
              .fontColor(this.type === FeedbackType.SUGGESTION ? $r('app.color.color_90ffffff') :
              $r('app.color.color_50ffffff'))
              .fontSize(14)
              .linearGradient({
                colors: [[this.type === FeedbackType.SUGGESTION ? '#F62C6C' : Color.Transparent, 0.0],
                  [this.type === FeedbackType.SUGGESTION ? '#FC4F54' : Color.Transparent, 1.0]],
                direction: GradientDirection.Right
              })
              .backgroundColor(this.type === FeedbackType.SUGGESTION ? Color.Transparent : $r('app.color.color_222222'))
              .borderRadius(4)
              .padding({ left: 14, right: 14 })
              .onClick(() => {
                this.type = FeedbackType.SUGGESTION
              })

            Button('功能异常', { type: ButtonType.Normal })
              .height(32)
              .fontColor(this.type === FeedbackType.BUG ? $r('app.color.color_90ffffff') :
              $r('app.color.color_50ffffff'))
              .fontSize(14)
              .linearGradient({
                colors: [[this.type === FeedbackType.BUG ? '#F62C6C' : Color.Transparent, 0.0],
                  [this.type === FeedbackType.BUG ? '#FC4F54' : Color.Transparent, 1.0]],
                direction: GradientDirection.Right
              })
              .backgroundColor(this.type === FeedbackType.BUG ? Color.Transparent : $r('app.color.color_222222'))
              .borderRadius(4)
              .padding({ left: 14, right: 14 })
              .margin({ left: 12 })
              .onClick(() => {
                this.type = FeedbackType.BUG
              })

            Button('其他问题', { type: ButtonType.Normal })
              .height(32)
              .fontColor(this.type === FeedbackType.OTHER ? $r('app.color.color_90ffffff') :
              $r('app.color.color_50ffffff'))
              .fontSize(14)
              .linearGradient({
                colors: [[this.type === FeedbackType.OTHER ? '#F62C6C' : Color.Transparent, 0.0],
                  [this.type === FeedbackType.OTHER ? '#FC4F54' : Color.Transparent, 1.0]],
                direction: GradientDirection.Right
              })
              .backgroundColor(this.type === FeedbackType.OTHER ? Color.Transparent : $r('app.color.color_222222'))
              .borderRadius(4)
              .padding({ left: 14, right: 14 })
              .margin({ left: 12 })
              .onClick(() => {
                this.type = FeedbackType.OTHER
              })
          }.width('100%')
          .margin({ top: 16 })

          Row() {
            Text('问题描述').fontColor($r('app.color.color_90ffffff')).fontSize(14)
            Text('*').fontColor('#FF3838')
          }
          .width('100%')
          .margin({ top: 20 })

          RelativeContainer() {
            TextArea({ placeholder: '请输入详情内容' })
              .height('100%')
              .placeholderColor($r('app.color.color_30ffffff'))
              .placeholderFont({ size: 14 })
              .fontSize(14)
              .fontColor($r('app.color.color_80ffffff'))
              .maxLength(200)
              .borderRadius(8)
              .backgroundColor($r('app.color.color_222222'))
              .onChange((value: string) => {
                this.contentText = value
              })

            Text(`${this.contentText.length}/200`).fontColor($r('app.color.color_999999')).fontSize(10)
              .alignRules({
                right: { anchor: '__container__', align: HorizontalAlign.End },
                bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
              })
              .margin({ right: 8, bottom: 8 })
          }.height(142).margin({ top: 16 })

          Row() {
            Text('上传图片').fontColor($r('app.color.color_90ffffff')).fontSize(14)
            Text('（选填，最多可上传3张）').fontColor($r('app.color.color_999999')).fontSize(10)
          }
          .width('100%')
          .margin({ top: 20 })

          Grid() {
            ForEach(this.selectedPhotos, (item: string, index) => {
              GridItem() {
                AddImageItemView({ uri: item, index: index, onDelete: (uri) => {
                  for (let i = 0; i < this.selectedPhotos.length; i++) {
                    const photo = this.selectedPhotos[i];
                    if (photo === uri) {
                      this.selectedPhotos.splice(i, 1)
                      this.selectedUris.splice(i, 1)
                      break
                    }
                  }
                } })
              }
            })
            GridItem() {
              AddImageItemView({index: this.selectedPhotos.length})
                .onClick(() => {
                  PhotoHelper.select({
                    MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
                    maxSelectNumber: 3,
                    preselectedUris: this.selectedUris,
                    isOriginalSupported: false
                  })
                    .then((result: photoAccessHelper.PhotoSelectResult) => {
                      if (result.photoUris.length > 0) {
                        this.selectedPhotos = result.photoUris
                        this.selectedUris = result.photoUris
                      }
                    })
                    .catch((e: BusinessError) => {
                      ToastUtils.show(e.message)
                    })
                })
            }
            .visibility(this.selectedImages.length < 3 ? Visibility.Visible : Visibility.None)
          }
          .width('100%')
          .height(80)
          .scrollBar(BarState.Off)
          .columnsTemplate('1fr 1fr 1fr')
          .margin({ top: 16 })

          Row() {
            Text('联系方式').fontColor($r('app.color.color_90ffffff')).fontSize(14)
            Text('（选填，可留下您的手机号、微信、邮箱）').fontColor($r('app.color.color_999999')).fontSize(10)
          }
          .width('100%')
          .margin({ top: 20 })

          TextInput({ placeholder: '请输入您的联系方式' })
            .height(50)
            .placeholderColor($r('app.color.color_30ffffff'))
            .placeholderFont({ size: 14 })
            .fontSize(14)
            .fontColor($r('app.color.color_80ffffff'))
            .maxLength(200)
            .borderRadius(8)
            .backgroundColor($r('app.color.color_222222'))
            .margin({ top: 16 })
            .onChange((value: string) => {
              this.contactText = value
            })
        }
        .height('100%')
        .padding({ left: 16, right: 16 })
      }
      .scrollBar(BarState.Off)
      .layoutWeight(1)
      .margin({ top: 16 })

      Stack() {
        Button('提交', { type: ButtonType.Capsule, stateEffect: true })
          .fontColor(Color.White)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .linearGradient({
            colors: [['#F62C6C', 0.0], ['#FC4F54', 1.0]],
            direction: GradientDirection.Right
          })
          .width('100%')
          .height(46)
          .onClick(() => {
            this.commit()
          })
      }
      .padding({ left: 16, right: 16 })
      .margin({ bottom: 30 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}