import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils';
import { ImageUtils } from '@ohos/common/src/main/ets/utils/ImageUtils';
import { TitleBarComponent } from '../view/TitleBarComponent';
import { ImageInfo, UploadInfo } from '../viewmodel/DataBean';
import { MainService } from '../viewmodel/MainService';

@Builder
export function FeedbackBuilder() {
  FeedbackLayout()
}

/**
 * 意见反馈页面
 */
@Component
export struct FeedbackLayout {
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;
  // 数据源
  private options: string[] = ['功能问题', '优化建议', '其他'];
  // item1 意见类型单选框索引
  @State selectedIndex: number = 0;
  // item2 补充意见输入框文字
  @State textCommentsValue: string = '';
  // item3 意见图片
  @State selectedImages: string[] = []; // 存储选中的图片路径
  private maxCount: number = 3; // 最大选择数量
  // item4 联系方式输入框文字
  @State textContactValue: string = '';
  // 文件上传结果
  @State uploadResult: UploadInfo[] = [];
  @State uploadStatus: Record<string, boolean> = {};

  // 调用系统相册选择器
  async selectImage() {
    try {
      let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      PhotoSelectOptions.maxSelectNumber = this.maxCount - this.selectedImages.length;

      let photoPicker = new photoAccessHelper.PhotoViewPicker();
      let photoSelectResult = await photoPicker.select(PhotoSelectOptions);

      if (photoSelectResult.photoUris.length > 0) {
        this.selectedImages = this.selectedImages.concat(photoSelectResult.photoUris);
        // 开始一张张上传
        for (const uri of photoSelectResult.photoUris) {
          try {
            this.uploadStatus[uri] =  true;
            const imageBase64 = await ImageUtils.base64Image(uri);
            await MainService.uploadImageBase64(imageBase64, {
              onSuccess: (data) => {
                let successInfo: UploadInfo = {
                  isSuccess: true,
                  message: '上传成功',
                  data: data as ImageInfo
                };
                this.uploadResult.push(successInfo);
                this.uploadStatus[uri] =  false;
              },
              onFailure: (message) => {
                let failureInfo: UploadInfo = {
                  isSuccess: false,
                  message: message,
                  data: undefined
                };
                this.uploadResult.push(failureInfo);
                this.uploadStatus[uri] =  false;

                ToastUtils.showToast(this.getUIContext(), message);
              },
              onError: (err) => {
                let errorInfo: UploadInfo = {
                  isSuccess: false,
                  message: err.message,
                  data: undefined
                };
                this.uploadResult.push(errorInfo);
                this.uploadStatus[uri] =  false;

                ToastUtils.showToast(this.getUIContext(), '上传失败');
              }
            });
          } catch (e) {
            // 如果某一张报错，会跳到这里。
            // 如果你想“某张失败后停止后续上传”，就在这里 break;
            // 如果想“不管失败继续下一张”，就什么都不写。
            console.error("顺序上传中断或出错");
            this.uploadStatus[uri] =  false;
          }
        }
        console.error("所有图片上传完成");
      }
    } catch (err) {
      let error: BusinessError = err as BusinessError;
      console.error('PhotoViewPicker.select failed: ' + JSON.stringify(error));
    }
  }

  build() {
    NavDestination() {
      Stack() {
        Scroll(){
          Column() {
            //标题栏
            TitleBarComponent({titleName:'问题反馈', isShowTitle:true, isShowBack:true})

            // 内容区
            Column() {
              // item1 标题
              Row(){
                Text('*')
                  .fontSize(16)
                  .fontColor('#FFEA0000')
                Text('您想反馈的功能类型')
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .layoutWeight(1)
                  .fontColor('#FF1A1A1A')
              }
              .padding({ left: 16, right: 16 })
              Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
                ForEach(this.options, (item: string, index: number) => {
                  Text(item)
                    .fontSize(14)
                    .fontColor(this.selectedIndex === index ? '#FFC2FF43' : '#FF1A1A1A')
                    .textAlign(TextAlign.Center)
                    .layoutWeight(1) // 平分宽度
                    .padding({ top: 10, bottom: 10 })
                    .margin({ left: 5, right: 5 })
                    // 选中状态与非选中状态的背景切换
                    .backgroundColor(this.selectedIndex === index ? '#FF252525' : '#FFFFFF')
                    .borderWidth(1)
                    .borderColor(this.selectedIndex === index ? Color.Transparent : '#FFD8D8D8')
                    .borderRadius(8)
                    // 点击切换索引
                    .onClick(() => {
                      this.selectedIndex = index;
                    })
                }, (item: string) => item)
              }
              .width('100%')
              .padding(16)

              // item2 标题
              Row(){
                Text('*')
                  .fontSize(16)
                  .fontColor('#FFEA0000')
                Text('请补充详细问题或意见')
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .layoutWeight(1)
                  .fontColor('#FF1A1A1A')
              }
              .padding({ left: 16, right: 16 })

              Stack({ alignContent: Alignment.BottomEnd }) {
                TextArea({ placeholder: '请在这里输入内容' })
                  .height(150)
                  .width('100%')
                  .backgroundColor('#FFF2F2F2')
                  .borderRadius(12)
                  .padding({ bottom: 30 }) // 留出底部空间给字数统计
                  .maxLength(200)
                  .onChange((v) => this.textCommentsValue = v)

                // 手动写字数统计
                Text(`${this.textCommentsValue.length}/200`)
                  .fontSize(12)
                  .fontColor('#FFAAAAAA')
                  .margin({ right: 12, bottom: 12 })
              }
              .padding(16)

              // item3 标题(选填)
              Row(){
                Text('请补充详细问题或意见')
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .fontColor('#FF1A1A1A')

                Text('（选填，最多可上传三张）')
                  .fontSize(11)
                  .textAlign(TextAlign.Start)
                  .layoutWeight(1)
                  .fontColor('#FFAAAAAA')
              }
              .padding({ left: 16, right: 16 })

              Row({ space: 10 }) {
                // 1. 循环显示已选中的图片
                ForEach(this.selectedImages, (uri: string, index: number) => {
                  /*
                  Stack(){
                    Stack({ alignContent: Alignment.TopEnd }) {
                      Image(uri)
                        .width(80)
                        .height(80)
                        .borderRadius(8)
                        .objectFit(ImageFit.Cover)

                      // 删除按钮
                      Circle({ width: 20, height: 20 })
                        .fill('#80000000')
                        .onClick(() => this.selectedImages.splice(index, 1))
                      Text('×').fontColor(Color.White).fontSize(14).margin({ right: 5 })
                    }
                  }
                  */

                  Stack({ alignContent: Alignment.Center }) {
                    // 1. 底层：图片
                    Image(uri)
                      .width(80)
                      .height(80)
                      .borderRadius(8)
                      .objectFit(ImageFit.Cover)

                    // 2. 中层：右上角删除按钮 (Stack 嵌套实现)
                    Stack({ alignContent: Alignment.TopEnd }) {
                      // 占位透明块，撑开点击区域
                      Rect().width(80).height(80).fill(Color.Transparent)

                      // 实际按钮内容
                      Stack({ alignContent: Alignment.Center }) {
                        Circle({ width: 20, height: 20 }).fill('#80000000')
                        Text('×').fontColor(Color.White).fontSize(14).textAlign(TextAlign.Center)
                      }
                      .offset({ x: 5, y: -5 }) // 往右上角偏移一点，视觉效果更好
                      .onClick(() => {
                        MainService.deleteImage((this.uploadResult[index].data?.id || ''), {
                          onSuccess: (_) => {
                            this.selectedImages.splice(index, 1);
                            this.uploadResult.splice(index, 1);
                            },
                          onFailure: (message) => {
                            ToastUtils.showToast(this.getUIContext(), message);
                          },
                          onError: () => {
                            ToastUtils.showToast(this.getUIContext(), '删除失败');
                          }
                        });
                      })
                    }
                    .width(80)
                    .height(80)

                    // 3. 顶层：圆形加载效果 (仅在加载时显示)
                    if (this.uploadStatus[this.selectedImages[index]] === true) {
                      LoadingProgress()
                        .width(30)
                        .height(30)
                        .color('#CCCCCC') // 设置旋转圆圈的颜色
                    }
                  }
                })

                // 2. 添加按钮（当数量小于 3 时显示）
                if (this.selectedImages.length < this.maxCount) {
                  Column() {
                    Image($r('app.media.ic_image_add')) // 替换为你图片中的虚线加号图标
                      .width(24)
                      .height(24)
                  }
                  .width(80)
                  .height(80)
                  .backgroundColor('#FFF2F2F2')
                  .borderRadius(8)
                  .justifyContent(FlexAlign.Center)
                  .onClick(() => this.selectImage())
                }
              }
              .width('100%')
              .padding(16)

              // item4 标题(选填)
              Row(){
                Text('联系方式')
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .fontColor('#FF1A1A1A')

                Text('（选填，可以留下您的手机号、微信、邮箱）')
                  .fontSize(11)
                  .textAlign(TextAlign.Start)
                  .layoutWeight(1)
                  .fontColor('#FFAAAAAA')
              }
              .padding({ left: 16, right: 16 })

              Stack({ alignContent: Alignment.BottomEnd }) {
                TextInput({ placeholder: '请输入您的联系方式', text: this.textContactValue })
                  .width('100%')
                  .backgroundColor('#FFF2F2F2')
                  .borderRadius(12)
                  .maxLength(20)
                  .type(InputType.PhoneNumber)
                  .onChange((v) => this.textContactValue = v)
              }
              .padding(16)

            }

          }
          .width('100%')
          .height('100%')
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        //提交按钮
        Stack() {
          Button('提交')
            .width('100%')
            .height(48)
            .fontSize(16)
            .fontColor('#FFC2FF43')
            .backgroundColor('#FF252525')
            .borderRadius(359)
            .onClick(() => {
              // 提交逻辑
              if(!this.textCommentsValue){
                ToastUtils.showToast(this.getUIContext(), '请填写反馈内容');
                return
              }
              const type = this.options[this.selectedIndex]
              const images: string[] = []
              for (let i = 0; i < this.uploadResult.length; i++) {
                images.push(this.uploadResult[i].data?.url || '')
              }
              MainService.feedback(type, this.textCommentsValue, this.textContactValue, images,{
                onSuccess: (_) => {
                  ToastUtils.showToast(this.getUIContext(), '感谢您的反馈');
                },
                onFailure: (message) => {
                  ToastUtils.showToast(this.getUIContext(), '对不起，提交失败');
                },
                onError: () => {
                  ToastUtils.showToast(this.getUIContext(), '出错啦~');
                }
              });
            })
        }
        .margin({ left: 16, right: 16, bottom: 32 })
      }
      .width('100%')
      .height('100%')
      .backgroundColor('#FFFFFFFF')
      .alignContent(Alignment.Bottom)
    }
    .hideTitleBar(true)
  }


}
