// 定义模板类型枚举
export enum TemplateTypeList {
  TreeView = 0,
  Expander = 1,
  Menu = 2
}

// 定义触发模式枚举
export enum TargetModeList {
  SingleClick = 0,
  DoubleClick = 1
}

// 定义菜单项数据类型
interface TradeItem {
  IsLeaf: boolean;
  Node: { Code: string };
  IsSelected?: boolean;
  IsExpanded?: boolean;
  Parent?: TradeItem;
  Children?: TradeItem[];
}

// 定义 TradeMenu 类
export class TradeMenu {
  // 依赖属性模拟
  TemplateType: TemplateTypeList = TemplateTypeList.TreeView;
  TargetMode: TargetModeList = TargetModeList.DoubleClick;
  IndentSize: number = 10.0;
  // 事件处理函数
  private _itemClickHandlers: ((code: string) => void)[] = [];
  private itemsSource: TradeItem[] = [];

  // 构造函数
  constructor() {
    // 模拟加载完成事件
    this.triggerLoaded();
  }

  private triggerLoaded() {
    switch (this.TargetMode) {
      case TargetModeList.DoubleClick:
        // 模拟双击事件绑定
        console.log('绑定双击事件');
        break;
      case TargetModeList.SingleClick:
        // 模拟单击事件绑定
        console.log('绑定单击事件');
        break;
    }
  }

  // 模拟菜单项点击事件处理
  private tradeMenuItemClick(code: string) {
    const item = this.getTradeItem(code);
    if (item && item.IsLeaf) {
      this._itemClickHandlers.forEach(handler => handler(code));
      this.setSelectItem(code);
    }
  }

  // 根据代码查找交易项
  private getTradeItem(code: string): TradeItem | null {
    let result: TradeItem | null = null;
    const findItem = (items: TradeItem[]) => {
      for (const item of items) {
        if (item.IsLeaf && item.Node.Code === code) {
          result = item;
          break;
        }
        if (item.Children) {
          findItem(item.Children);
        }
      }
    };
    findItem(this.itemsSource);
    return result;
  }

  // 设置选中项
  setSelectItem(code: string): boolean {
    if (!code) {
      const unselectAll = (items: TradeItem[]) => {
        for (const item of items) {
          item.IsSelected = false;
          if (item.Children) {
            unselectAll(item.Children);
          }
        }
      };
      unselectAll(this.itemsSource);
      return true;
    }

    const item = this.getTradeItem(code);
    if (item) {
      item.IsSelected = true;
      item.IsExpanded = true;
      let node = item;
      while (node.Parent) {
        node.Parent.IsExpanded = true;
        node = node.Parent;
      }
    }
    return true;
  }

  // 绑定事件处理函数
  onItemClick(handler: (code: string) => void) {
    this._itemClickHandlers.push(handler);
  }
}