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

import { Component } from "cc";
import { Tips } from "../../scripts/mgr/Tips";
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.addComponent(Button);
    }

    tpl.on(Button.EventType.CLICK, this.Q_Click_Tab, this);

    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 t = this.node.children[i].getChildByName("value").getComponent(Label);
      t.string = titles[i];
      this.node.children[i].getComponent(UITransform).width =
        titles[i].length * 15 + 10;
 
      if (i == 0) {
        t.color = new Color(192, 242, 131, 255);
      } else {
        t.color = new Color(255, 255, 255, 255);
      }
    }

    // this.setSelect(0);
  }

  public resizeItem(width: number) {
    for (let i = 0; i < this.node.children.length; i++) {
      this.node.children[i].getComponent(UITransform).width = width;
    }
  }

  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 = 0;
  Q_Click_Tab(event: any) {
    let index = parseInt(event.target.name.split("_")[1]);
    if (index == this._selectIndex) return;
    console.log("Q_Click_Tab 111", index);
    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);
  }
}
