import { instantiate } from "cc";
import { _decorator, Node } from "cc";
import { Label } from "cc";

import { Component } from "cc";
import { Button } from "cc";
import { UITransform } from "cc";
import { Color } from "cc";
const { ccclass, property } = _decorator;

export interface OnTabClickListener {
  onTabClick(index: number);
}

@ccclass("CommonTabsTitle")
export class CommonTabsTitle extends Component {
  private _clickDisableIndexes: number[] = [];
  setClickDisableIndexes(indexes: number[]) {
    this._clickDisableIndexes = indexes;
  }

  public get selectIndex(): number {
    return this._selectIndex;
  }

  private _listener: OnTabClickListener;
  public init(titles: string[], listener: OnTabClickListener) {
    this._listener = listener;
    let tpl = this.node.children[0];

    if (tpl.getComponent(Button) != null) {
      tpl.getComponent(Button).clickEvents = [];
    } else {
      tpl.addComponent(Button);
    }

    for (let i = this.node.children.length; i < titles.length; i++) {
      let tab = instantiate(tpl);
      tab.name = "tab_" + i;
      tab.setParent(this.node);
    }

    for (let i = 0; i < this.node.children.length; i++) {
      let tab = this.node.children[i];
      tab.on(Button.EventType.CLICK, this.Q_Click_Tab, this);
      let t = tab.getChildByName("value").getComponent(Label);
      t.string = titles[i];
    }

    // this.setSelect(0);
  }

  public setSelect(index: number) {
    if (index == this._selectIndex) return;
    for (let i = 0; i < this.node.children.length; i++) {
      this.node.children[i].getChildByName("select").active = i == index;
      //   this.node.children[i].getChildByName("value").getComponent(Label).color =
      //     i != index
      //       ? new Color(255, 255, 255, 255)
      //       : new Color(192, 242, 131, 255);
    }
    this._selectIndex = index;
  }
  private _selectIndex: number = -1;
  Q_Click_Tab(event: any) {
    console.log("Q_Click_Tab 222", event.target.name);

    let index = parseInt(event.target.name.split("_")[1]);
    if (index == this._selectIndex) return;
    if (
      this._clickDisableIndexes &&
      this._clickDisableIndexes.indexOf(index) != -1
    ) {
      // 不可点击的tab
      // Tips.show("Coming soon");
      return;
    }

    this.setSelect(index);
    this._selectIndex = index;

    console.log("onTabClick", index);
    console.log(this._listener);
    this._listener.onTabClick(index);
  }
}
