import { UIContext, ComponentContent, promptAction } from '@kit.ArkUI';
import deviceInfo from '@ohos.deviceInfo';

interface ToastParams {
  message: string;
}
// 1.定义包裹组件 (保持不变)
@Component
struct Toast {
  @Prop message: string = '';
  build() {
    Stack(){
      Text(this.message)
        .fontSize(12)
        .fontColor('#FFFFFF')
        .textAlign(TextAlign.Center)
        .margin(12)
    }
    .width(100)
    .height(100)
    .backgroundColor('#cc000000')
    .borderRadius(16)
  }
}

// 2.包装 Builder (跨模块调用的核心)
@Builder
function toastBuilder(params: ToastParams) {
  Toast({ message: params.message })
}

export class ToastUtils {
  private static content: ComponentContent<ToastParams> | null = null;

  static showToast(uiContext: UIContext, message: string, duration: number = 2000): void {
    // 如果已有弹窗，先关闭旧的
    if (ToastUtils.content) {
      uiContext.getPromptAction().closeCustomDialog(ToastUtils.content);
    }

    // 3.在创建 ComponentContent 时，第三个参数传入数据对象
    const params: ToastParams = { message: message };
    ToastUtils.content = new ComponentContent(uiContext, wrapBuilder(toastBuilder), params);

    const prompt = uiContext.getPromptAction();

    prompt.openCustomDialog(ToastUtils.content, {
      autoCancel: true,
      alignment: DialogAlignment.Center,
      maskColor: '#00000000'
    }).then(() => {
      setTimeout(() => {
        if (ToastUtils.content) {
          prompt.closeCustomDialog(ToastUtils.content);
          ToastUtils.content = null;
        }
      }, duration);
    });
  }

  static normalToast(options: ToastOptions): void {
    // 设置默认值
    const message = options.message;
    const duration = options.duration ?? 2000;
    const bottom = options.bottom ?? '80%'; // 系统的默认位置通常在底部

    if (deviceInfo.sdkApiVersion < 18) {
      promptAction.showToast({
        message: message,
        duration: duration,
        bottom: bottom
      });
    } else {
      promptAction.openToast({
        message: message,
        duration: duration,
        bottom: bottom
      });
    }
  }
}

interface ToastOptions {
  message: string;
  duration?: number; // 可选
  bottom?: string | number; // 可选
}