import { Logger } from "@ohos/common";
import { router } from "@kit.ArkUI";

/**
 * 通用TitleBar component.
 */
@Component
export struct TitleBarComponent {
  @State titleName: string = '';
  @State isShowTitle: boolean = true;
  @State isShowBack: boolean = true;
  @State isShowSave: boolean = false;
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;

  onSave?: () => void;

  build() {
    Column() {
      //标题栏
      Row() {
        if(this.isShowBack){
          Image($r('app.media.ic_back_arrow'))
            .width('24vp')
            .height('24vp')
            .onClick(() => {
              // 1. 先尝试从 NavPathStack 返回（针对 Navigation 内部子页）
              if (this.pageStack.size() > 0) {
                this.pageStack.pop();
                Logger.info('TitleBarComponent', 'NavStack 返回');
              } else {
                // 2. 如果栈为空，说明是 router 页面，执行 router 返回
                router.back();
                Logger.info('TitleBarComponent', 'Router 返回');
              }
            })
        }

        Stack(){
          if(this.isShowTitle){
            Text(this.titleName)
              .fontSize(16)
              .fontColor('#FF1A1A1A')
              .layoutWeight(1)
              .textAlign(TextAlign.Center)
              .margin({ right: 24 })
          }
        }
        .layoutWeight(1)
        .alignContent(Alignment.Center)

        if(this.isShowSave){
          Button('保存')
            .width('60vp')
            .height('30vp')
            .fontSize(14)
            .fontColor('#FFC2FF43')
            .borderRadius(359)
            .backgroundColor('#FF000000')
            .onClick(() => {
              // 保存
              if (this.onSave) {
                this.onSave();
              }
            })
            .align(Alignment.End)
        }
      }
      .width('100%')
      .height('56vp')
      .margin({ top: this.statusBarHeight})
      .alignItems(VerticalAlign.Center)
      .padding({ left: 16, right: 16 })
    }
  }
}