import { _decorator, Component, Node, Event } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { Hall } from "../hall/Hall";
import { RichText } from "cc";
import { Label } from "cc";
const { ccclass, property } = _decorator;

export class TipsData {
  forceConfirm: boolean = false;
  title: string;
  content: string;
  onConfirm: () => void = null;
  singleName: string = "";
  link: string = null;
}

export interface OnConfirm {
  (): void;
}

@ccclass("TipsLayer")
export class TipsLayer extends BaseUI {
  static confirm(title: string, content: string) {
    return new Promise((resolve, reject) => {
      let tipsData: TipsData = {
        title: title,
        link: null,
        content: content,
        onConfirm: () => {
          resolve(true);
        },
        forceConfirm: true,
        singleName: null,
      };
      TipsLayer.show(tipsData);
    });
  }
  private onConfirm: OnConfirm = null;
  private static single: Map<string, Node> = new Map();
  static async show(data: TipsData): Promise<TipsLayer> {
    if (data.singleName) {
      if (TipsLayer.single.has(data.singleName)) {
        return TipsLayer.single.get(data.singleName).getComponent(TipsLayer);
      }
    }

    let layer = await Hall.ins.showLayer("prefab/layer/TipsLayer");
    let comp = layer.getComponent(TipsLayer);
    comp.init(data);
    if (data.singleName) {
      TipsLayer.single.set(data.singleName, layer);
    }
    return comp;
  }

  private data: TipsData;
  init(data: TipsData) {
    this.data = data;
    if (data.title == null || data.title == "") {
      this.FindNode("lbl_title").active = false;
    } else {
      this.setText("lbl_title", data.title);
    }
    // this.setText("lbl_content", data.content);

    this.FindAs("lbl_content", RichText).string = data.content;

    if (data.forceConfirm) {
      this.FindNode("tap_close").active = false;
      this.FindNode("btn_close").active = false;
      this.FindNode("close_obj").active = false;
    }

    this.FindNode("btn_link").active = data.link != null;
    this.FindNode("btn_link").getComponent(Label).string = data.link;
    // this.setText("btn_link", data.link);
  }

  protected onBtnClick(name: string, event: Event, customEventData: any): void {
    if (name == "btn_confirm") {
      this.data?.onConfirm?.();
      this.closePage();
    }
  }
  protected onDestroy(): void {
    if (this.data?.singleName) {
      TipsLayer.single.delete(this.data.singleName);
    }
  }

  protected simpleOnBtnClick(name: string): void {
    if (name == "btn_link") {
      let url = this.FindNode("btn_link").getComponent(Label).string;
      window.open(url, "_blank");
    }
  }
}
